Quote some missed file names (#50193)

Mostly in section headers, but elsewhere too.

Also switch from `<my package>` to `<my-package>`.
This commit is contained in:
Eli Barzilay
2020-12-19 05:02:49 -05:00
committed by GitHub
parent 4fbb00eb5c
commit 9b02f6817a
7 changed files with 125 additions and 125 deletions

View File

@@ -22,10 +22,10 @@
- [创建一个新的包](#创建一个新的包)
- [删除一个包](#删除一个包)
- [验证](#验证)
- [\<my package>-tests.ts](#my-package-teststs)
- [`<my-package>-tests.ts`](#my-package-teststs)
- [Linter: `tslint.json`](#linter-tslintjson)
- [tsconfig.json](#tsconfigjson)
- [package.json](#packagejson)
- [`tsconfig.json`](#tsconfigjson)
- [`package.json`](#packagejson)
- [常见错误](#常见错误)
</details>
- [Definition Owners](#definition-owners)
@@ -178,12 +178,12 @@ Version | Released | End of Support
| 文件名 | 目的 |
| --- | --- |
| index.d.ts | 这里包含了包的类型声明。 |
| [\<my package>-tests.ts](#my-package-teststs) | 这里包含了测试类型的示例代码,此代码 **不会** 运行,但是它需要通过类型检查。 |
| [tsconfig.json](#tsconfigjson) | 这里允许你在包里运行 `tsc`. |
| [tslint.json](#linter-tslintjson) | 启用 linting. |
| `index.d.ts` | 这里包含了包的类型声明。 |
| [`<my-package>-tests.ts`](#my-package-teststs) | 这里包含了测试类型的示例代码,此代码 **不会** 运行,但是它需要通过类型检查。 |
| [`tsconfig.json`](#tsconfigjson) | 这里允许你在包里运行 `tsc`. |
| [`tslint.json`](#linter-tslintjson) | 启用 linting. |
如果你的 npm ≥ 5.2.0,运行 `npx dts-gen --dt --name <my package> --template module` 来生成这些文件,否则就运行 `npm install -g dts-gen` 和 `dts-gen --dt --name <my package> --template module`.
如果你的 npm ≥ 5.2.0,运行 `npx dts-gen --dt --name <my-package> --template module` 来生成这些文件,否则就运行 `npm install -g dts-gen` 和 `dts-gen --dt --name <my-package> --template module`.
可以在 [dts-gen](https://github.com/Microsoft/dts-gen) 查看所有的选项。
Definitely Typed 的成员会定期查看新的 PRs但是请记住当有许多其他 PRs 的时候,检查会变慢。
@@ -197,7 +197,7 @@ Definitely Typed 的成员会定期查看新的 PRs但是请记住当有许
你可以运行以下命令来删除它 `npm run not-needed -- typingsPackageName asOfVersion [libraryName]`.
- `typingsPackageName`: 这是你要删除的目录名字.
- `asOfVersion`: 将使用此版本将存根发布到 `@types/foo`. 版本号应该高于当前发布的任何版本,并且应该是 npm 上的 `foo` 版本。
- `libraryName`: 替换 Definitely Typed 中类型的 npm 的包名。通常这与 "typingsPackageName" 相同,这种情况下你可以忽略它。
- `libraryName`: 替换 Definitely Typed 中类型的 npm 的包名。通常这与 `typingsPackageName` 相同,这种情况下你可以忽略它。
Definitely Typed 中其他引用了删除包的任何包,都需要去更新去引用新的捆绑类型。
你可以查看 `npm test` 中的错误来获得此列表。
@@ -222,14 +222,14 @@ Definitely Typed 中其他引用了删除包的任何包,都需要去更新去
通过运行 `npm test <package to test>` 去测试你的改动,其中 `<package to test>` 是你的包名。
这个脚本使用了 [dtslint](https://github.com/Microsoft/dtslint).
#### \<my package>-tests.ts
#### `<my-package>-tests.ts`
There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.
There should be a `<my-package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my-package>`.
Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`
For example, this change to a function in a `.d.ts` file adding a new param to a function:
@@ -240,7 +240,7 @@ For example, this change to a function in a `.d.ts` file adding a new param to a
+ export function twoslash(body: string, config?: { version: string }): string
```
`<my package>-tests.ts`:
`<my-package>-tests.ts`:
```diff
import {twoslash} from "./"
@@ -277,13 +277,13 @@ The linter configuration file, `tslint.json` should contain `{ "extends": "dtsli
If for some reason some rule needs to be disabled, [disable it for that specific line](https://palantir.github.io/tslint/usage/rule-flags/#comment-flags-in-source-code:~:text=%2F%2F%20tslint%3Adisable%2Dnext%2Dline%3Arule1%20rule2%20rule3...%20%2D%20Disables%20the%20listed%20rules%20for%20the%20next%20line) using `// tslint:disable-next-line:[ruleName]` — not for the whole package, so that disabling can be reviewed. (There are some legacy lint configs that have additional contents, but these should not happen in new work.)
#### tsconfig.json
#### `tsconfig.json`
`tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
你可以编辑 `tsconfig.json` 来增加新文件,增加 `"target": "es6"` (异步函数需要),去增加 `"lib"`,或者增加 `"jsx"` 编译选项。
#### package.json
#### `package.json`
通常你不需要它。
Definitely Typed 包的发布者会为在 Definitely Typed 之外没有依赖的包创建一个 `package.json` 文件。
@@ -515,9 +515,9 @@ _注意本节中的讨论假定你熟悉 [语义版本控制](https://semver.
#### 如何为可以在全局使用的包和作为模块的包编写类型定义?
TypeScript 手册包含了优秀的 [关于编写类型定义的概括信息](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), 以及 [此示例定义文件](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html),它展示了如何使用 ES6 模块语法创建定义,同时还指定了全局范围可用的对象。这个技术在 [big.js 的定义](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts) 得到了实际证明。该库可以通过网页上的脚本标记全局加载,也可以通过 require 或者 ES6 风格的风格导入。
TypeScript 手册包含了优秀的 [关于编写类型定义的概括信息](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), 以及 [此示例定义文件](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html),它展示了如何使用 ES6 模块语法创建定义,同时还指定了全局范围可用的对象。这个技术在 [`big.js` 的定义](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts) 得到了实际证明。该库可以通过网页上的脚本标记全局加载,也可以通过 require 或者 ES6 风格的风格导入。
要测试你的类型定义是否能全局引用或者作为模块导入,请创建一个 `test` 文件,并在其中放置两个测试文件。一个命名为 `YourLibraryName-global.test.ts`, 另一个为 `YourLibraryName-module.test.ts`. *全局* 测试文件应该根据如何在全局范围内库可用的网页上加载的脚本中使用它来执行定义,在这种情况下,你不应该制定 import 语句。*模块* 测试文件应该根据导入时的使用方式(包括 `import` 语句)来执行定义。如果在 `tsconfig.json` 文件中指定了 `files` 属性请确保包含了两个测试文件。big.js 定义中还提供了一个 [实际例子](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test)。
要测试你的类型定义是否能全局引用或者作为模块导入,请创建一个 `test` 文件,并在其中放置两个测试文件。一个命名为 `YourLibraryName-global.test.ts`, 另一个为 `YourLibraryName-module.test.ts`. *全局* 测试文件应该根据如何在全局范围内库可用的网页上加载的脚本中使用它来执行定义,在这种情况下,你不应该制定 import 语句。*模块* 测试文件应该根据导入时的使用方式(包括 `import` 语句)来执行定义。如果在 `tsconfig.json` 文件中指定了 `files` 属性,请确保包含了两个测试文件。`big.js` 定义中还提供了一个 [实际例子](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test)。
请注意,不需要在每个测试文件中完全执行定义 - 只需要在全局测试文件中测试全局可访问元素并在模块测试文件中完全执行定义,反之亦然。

View File

@@ -15,10 +15,10 @@ Vea también el sitio web [definitelytyped.org](http://definitelytyped.org), aun
- [Crear un nuevo paquete](#crear-un-nuevo-paquete)
- [Remover un paquete](#remover-un-paquete)
- [Running Tests](#running-tests)
- [\<my package>-tests.ts](#my-package-teststs)
- [`<my-package>-tests.ts`](#my-package-teststs)
- [Linter: `tslint.json`](#linter-tslintjson)
- [tsconfig.json](#tsconfigjson)
- [package.json](#packagejson)
- [`tsconfig.json`](#tsconfigjson)
- [`package.json`](#packagejson)
- [Errores comunes](#errores-comunes)
</details>
- [Definition Owners](#definition-owners)
@@ -166,12 +166,12 @@ Tu paquete debería tener esta estructura:
| Archivo | Propósito |
| --- | --- |
| index.d.ts | Este contiene los typings del paquete. |
| [\<my package>-tests.ts](#my-package-teststs) | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. |
| [tsconfig.json](#tsconfigjson) | Este permite ejecutar `tsc` dentro del paquete. |
| [tslint.json](#linter-tslintjson) | Permite linting. |
| `index.d.ts` | Este contiene los typings del paquete. |
| [`<my-package>-tests.ts`](#my-package-teststs) | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. |
| [`tsconfig.json`](#tsconfigjson) | Este permite ejecutar `tsc` dentro del paquete. |
| [`tslint.json`](#linter-tslintjson) | Permite linting. |
Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name <my package> --template module`.
Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name <my-package> --template module`.
Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen).
Los miembros de Definitely Typed frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrían ralentizar el proceso.
@@ -185,7 +185,7 @@ Cuando un paquete [bundles](http://www.typescriptlang.org/docs/handbook/declarat
Se puede remover ejecutando `npm run not-needed -- typingsPackageName asOfVersion [libraryName]`.
- `typingsPackageName`: Este es el nombre del directorio que tienes que eliminar.
- `asOfVersion`: Un stub será publicado a `@types/foo` con esta versión. Debería ser más grande que cualquier versión publicada actualmente.
- `libraryName`: Un nombre descriptivo de la librería, p.ej. "Angular 2" en vez de "angular2". (Si es omitido, será idéntico a "typingsPackageName".)
- `libraryName`: Un nombre descriptivo de la librería, p.ej. "Angular 2" en vez de "angular2". (Si es omitido, será idéntico a `typingsPackageName`.)
Cualquier otro paquete en Definitely Typed que referencie el paquete eliminado deberá ser actualizado para referenciar los tipos bundled. para hacer esto, [añade `package.json`](#packagejson) con `"dependencies": { "foo": "x.y.z" }`.
@@ -196,14 +196,14 @@ Si un paquete nunca estuvo en Definitely Typed, no será necesario añadirlo a `
Realiza una prueba ejecutando `npm test <package to test>` donde `<package to test>` es el nombre de tu paquete.
Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
#### \<my package>-tests.ts
#### `<my-package>-tests.ts`
There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.
There should be a `<my-package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my-package>`.
Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`
For example, this change to a function in a `.d.ts` file adding a new param to a function:
@@ -214,7 +214,7 @@ For example, this change to a function in a `.d.ts` file adding a new param to a
+ export function twoslash(body: string, config?: { version: string }): string
```
`<my package>-tests.ts`:
`<my-package>-tests.ts`:
```diff
import {twoslash} from "./"
@@ -251,18 +251,18 @@ The linter configuration file, `tslint.json` should contain `{ "extends": "dtsli
If for some reason some rule needs to be disabled, [disable it for that specific line](https://palantir.github.io/tslint/usage/rule-flags/#comment-flags-in-source-code:~:text=%2F%2F%20tslint%3Adisable%2Dnext%2Dline%3Arule1%20rule2%20rule3...%20%2D%20Disables%20the%20listed%20rules%20for%20the%20next%20line) using `// tslint:disable-next-line:[ruleName]` — not for the whole package, so that disabling can be reviewed. (There are some legacy lint configs that have additional contents, but these should not happen in new work.)
#### tsconfig.json
#### `tsconfig.json`
`tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`.
#### package.json
#### `package.json`
Normalmente no lo necesitarás. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente.
Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json.
Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al `package.json`.
#### Errores comunes
@@ -387,9 +387,9 @@ Además, `/// <reference types=".." />` no trabajará con rutas mapeadas, así q
#### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo?
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), además [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada prácticamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a través de una etiqueta script en una página web, o importada vía require o imports estilo ES6.
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), además [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada prácticamente en la [definición para `big.js`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a través de una etiqueta script en una página web, o importada vía require o imports estilo ES6.
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas una propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas una propiedad `files` en tu archivo `tsconfig.json`, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de `big.js`.
Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa.

View File

@@ -18,7 +18,7 @@
- [よくあるミス](#よくあるミス)
- [パッケージを削除する](#パッケージを削除する)
- [Linter](#linter)
- [\<パッケージ名>-tests.ts](#パッケージ名-teststs)
- [`<パッケージ名>-tests.ts`](#パッケージ名-teststs)
- [テストの実行](#テストの実行)
</details>
- [型定義のオーナー](#型定義のオーナー)
@@ -174,10 +174,10 @@ NPM 上にないパッケージの型定義を追加したい場合は、その
| ファイル | 用途 |
| ------------- | ---- |
| index.d.ts | 型定義が含まれる。 |
| [\<パッケージ名>-tests.ts](#パッケージ名-teststs) | 型定義をテストするサンプルコードが含まれる。このコードは実行は**されません**が、型チェックはされます。 |
| tsconfig.json | パッケージ内で `tsc` を実行するのに必要。 |
| tslint.json | Lint を有効にする。 |
| `index.d.ts` | 型定義が含まれる。 |
| [`<パッケージ名>-tests.ts`](#パッケージ名-teststs) | 型定義をテストするサンプルコードが含まれる。このコードは実行は**されません**が、型チェックはされます。 |
| `tsconfig.json` | パッケージ内で `tsc` を実行するのに必要。 |
| `tslint.json` | Lint を有効にする。 |
これらのファイルを生成するには、 npm 5.2.0 以上では `npx dts-gen --dt --name <パッケージ名> --template module` 、それより古い環境では `npm install -g dts-gen``dts-gen --dt --name <パッケージ名> --template module` を実行してください。
dts-gen の全オプションは[こちら](https://github.com/Microsoft/dts-gen)で確認できます。
@@ -221,7 +221,7 @@ Definitely Typed のメンバーは常に新しい PR をチェックしてい
`npm run not-needed -- typingsPackageName asOfVersion [libraryName]` を実行するとパッケージを削除できます。.
* `typingsPackageName`: 削除したいディレクトリ名。
* `asOfVersion`: `@types/foo` に対してスタブstubを公開したいバージョン。現在公開中のバージョンより新しく、かつ npm 上の `foo` のバージョンとあわせる必要があります。
* `libraryName`: Definitely Typed 側の型定義の代わりとなる npm のパッケージ名。基本的に "typingsPackageName" と一致し、その場合は省略できます。
* `libraryName`: Definitely Typed 側の型定義の代わりとなる npm のパッケージ名。基本的に `typingsPackageName` と一致し、その場合は省略できます。
削除されたパッケージを参照していた、他の Definitely Typed 上のパッケージは全て、ライブラリにバンドルされている型定義を参照するように更新する必要があります。
`npm run test-all` を実行した際のエラーを参照することで、更新が必要なライブラリのリストが確認できます。
@@ -265,7 +265,7 @@ Definitely Typed のメンバーは常に新しい PR をチェックしてい
(本当に適用させたくないルールがある場合は、 `// tslint:disable ルール名` か `//tslint:disable-next-line ルール名` (より良い)を使用してください。)
#### \<パッケージ名>-tests.ts
#### `<パッケージ名>-tests.ts`
パッケージには `<パッケージ名>-tests.ts` が必要です。このファイルは、ファイル内でインポートしている他の `*.ts` とあわせて、テスト用のファイルになります。
モジュールのフォルダにテスト用ファイルが見当たらない場合は、 `<パッケージ名>-tests.ts` を作成してください。
@@ -544,9 +544,9 @@ Definitely Typed の各パッケージは NPM に公開される際にバージ
#### グローバルにも使えてモジュールとしても使えるパッケージについては、どのように型定義すればよいですか?
TypeScript ハンドブックには、[型定義を書くにあたっての一般的な情報](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)がとてもよくまとめられており、また object をグローバル スコープで使えるようにしながら ES6 方式のモジュール構文を使って型定義を作成している[型定義ファイルの例](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)も掲載されています。この手法は実際に [big.js の型定義](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)で使われています。このモジュールはウェブページでは `<script>` タグでグローバルに読み込むことができ、 `require` や ES6 方式の `import` でインポートすることもできます。
TypeScript ハンドブックには、[型定義を書くにあたっての一般的な情報](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)がとてもよくまとめられており、また object をグローバル スコープで使えるようにしながら ES6 方式のモジュール構文を使って型定義を作成している[型定義ファイルの例](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)も掲載されています。この手法は実際に [`big.js` の型定義](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)で使われています。このモジュールはウェブページでは `<script>` タグでグローバルに読み込むことができ、 `require` や ES6 方式の `import` でインポートすることもできます。
型定義ファイルがグローバルにも、インポートされたモジュールとしても使用できるかをテストするには、次のようにします。まず `test` フォルダを作成し、そこに `YourLibraryName-global.test.ts` と `YourLibraryName-module.test.ts` の2つのファイルを用意します。 *global* テストファイルでは、ウェブページ上でスクリプトとして読み込まれ、ライブラリがグローバル スコープで使用可能になるようにテストします &mdash; このとき、インポート構文は使用してはいけません。 *module* テストファイルでは、 `import` 構文などを使用し、モジュールとしてインポートする方法に沿ってテストします。 `tsconfig.json` ファイル内で `files` プロパティを指定している場合は、両方をテストファイルを含めるのを忘れないでください。 big.js の型定義での[実際のテストファイル](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test)も参考にしてください。
型定義ファイルがグローバルにも、インポートされたモジュールとしても使用できるかをテストするには、次のようにします。まず `test` フォルダを作成し、そこに `YourLibraryName-global.test.ts` と `YourLibraryName-module.test.ts` の2つのファイルを用意します。 *global* テストファイルでは、ウェブページ上でスクリプトとして読み込まれ、ライブラリがグローバル スコープで使用可能になるようにテストします &mdash; このとき、インポート構文は使用してはいけません。 *module* テストファイルでは、 `import` 構文などを使用し、モジュールとしてインポートする方法に沿ってテストします。 `tsconfig.json` ファイル内で `files` プロパティを指定している場合は、両方をテストファイルを含めるのを忘れないでください。 `big.js` の型定義での[実際のテストファイル](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test)も参考にしてください。
両方のテストファイルで、型定義に対する完全なテストを行う必要はありません &mdash; *global* テストファイルではグローバルな要素にアクセスできるかのみをテストし、 *module* テストファイルで型定義の完全なテストを行う(またはその逆パターン)のでもかまいません。

View File

@@ -20,10 +20,10 @@
- [새 패키지를 만들기](#새-패키지를-만들기)
- [패키지 삭제하기](#패키지-삭제하기)
- [검증하기](#검증하기)
- [\<my package>-tests.ts](#my-package-teststs)
- [`<my-package>-tests.ts`](#my-package-teststs)
- [Linter: `tslint.json`](#linter-tslintjson)
- [tsconfig.json](#tsconfigjson)
- [package.json](#packagejson)
- [`tsconfig.json`](#tsconfigjson)
- [`package.json`](#packagejson)
- [많이 저지르는 실수들](#많이-저지르는-실수들)
</details>
- [Definition Owners](#definition-owners)
@@ -190,13 +190,13 @@ NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지
| 파일 이름 | 용도 |
| --- | --- |
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
| [\<my package>-tests.ts](#my-package-teststs) | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| [tsconfig.json](#tsconfigjson) | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
| [tslint.json](#linter-tslintjson) | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
| `index.d.ts` | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
| [`<my-package>-tests.ts`](#my-package-teststs) | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| [`tsconfig.json`](#tsconfigjson) | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
| [`tslint.json`](#linter-tslintjson) | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name <my package> --template module` 명령으로,
그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name <my package> --template module` 명령으로 만들 수 있습니다.
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name <my-package> --template module` 명령으로,
그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name <my-package> --template module` 명령으로 만들 수 있습니다.
`dts-gen` 의 모든 옵션(Option)을 보고싶으시면 [dts-gen](https://github.com/Microsoft/dts-gen) 저장소를 확인해주세요.
Definitely Typed 의 관리자들이 주기적으로 새로운 풀 리퀘스트(Pull request)들을 확인하기는 하지만,
@@ -211,7 +211,7 @@ Definitely Typed 의 관리자들이 주기적으로 새로운 풀 리퀘스트(
`npm run not-needed -- typingsPackageName asOfVersion [libraryName]` 명령어를 사용하여 자료형(Typing) 패키지를 삭제할 수 있습니다.
- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다.
- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다.
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.)
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 `typingsPackageName` 와 같은 것으로 취급됩니다.)
Definitely Typed 의 다른 패키지들이 삭제된 자료형(Typing) 패키지를 사용하고 있을 경우, 형(Type)을 포함하기 시작한 원래 패키지를 사용하도록 수정해야합니다. 삭제된 자료형(Typing) 패키지를 사용하는 각 Definitely Typed 패키지들의 [`package.json`](#packagejson) 파일에 `"dependencies": { "foo": "x.y.z" }` 를 추가해주시면 됩니다.
@@ -223,14 +223,14 @@ Definitely Typed 에 한 번도 올라온 적 없는 패키지가 형(Type)을
작성한 dts 파일을 타입스크립트 컴파일러로 돌려보기 위해 테스트 스크립트 내부적으로 [dtslint](https://github.com/Microsoft/dtslint)를 사용합니다.
#### \<my package>-tests.ts
#### `<my-package>-tests.ts`
There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.
There should be a `<my-package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my-package>`.
Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`
For example, this change to a function in a `.d.ts` file adding a new param to a function:
@@ -241,7 +241,7 @@ For example, this change to a function in a `.d.ts` file adding a new param to a
+ export function twoslash(body: string, config?: { version: string }): string
```
`<my package>-tests.ts`:
`<my-package>-tests.ts`:
```diff
import {twoslash} from "./"
@@ -278,13 +278,13 @@ The linter configuration file, `tslint.json` should contain `{ "extends": "dtsli
If for some reason some rule needs to be disabled, [disable it for that specific line](https://palantir.github.io/tslint/usage/rule-flags/#comment-flags-in-source-code:~:text=%2F%2F%20tslint%3Adisable%2Dnext%2Dline%3Arule1%20rule2%20rule3...%20%2D%20Disables%20the%20listed%20rules%20for%20the%20next%20line) using `// tslint:disable-next-line:[ruleName]` — not for the whole package, so that disabling can be reviewed. (There are some legacy lint configs that have additional contents, but these should not happen in new work.)
#### tsconfig.json
#### `tsconfig.json`
`tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
자료형(Typing) 패키지에 새 파일을 추가하거나, `async` 키워드를 사용하기 위해 `"target"` 을 `"es6"` 로 설정하거나, `"lib"` 를 추가하거나, `jsx` 지원을 추가하기 위해서 `tsconfig.json` 파일을 변경해야 할 수도 있습니다.
#### package.json
#### `package.json`
일반적으로는 `package.json` 파일을 사용할 필요가 없습니다. 패키지가 퍼블리시(Publish)될 때 패키지를 위한 `package.json` 파일은 자동으로 생성됩니다.
가끔 보이는 `package.json` 파일은 의존하는 것들을 표시하기 위해 사용됩니다. [예시](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json)를 한 번 보세요.
@@ -409,15 +409,15 @@ NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `
수정 중인 패키지에 의존하는 Definitely Typed 의 다른 패키지들이 새 버전과 호환되지 않을 경우, 그 패키지들에도 옛날 버전으로의 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다. 수정 중인 패키지에 의존하는 패키지에 의존하는 패키지들에도 똑같은 작업을 해 주셔야 합니다.
예를 들어, `react-router` 패키지는 `history@2` 패키지에 의존하고 있기 때문에, [react-router 패키지의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) 파일이 `"history": [ "history/v2" ]` 와 같은 경로 대응 규칙(Path mapping rule)을 가지고 있는 걸 볼 수 있습니다.
이어서 (`react-router` 패키지에 의존하는 패키지인) `react-router-bootstrap` 또한 [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json) 파일 안에 경로 대응 규칙(Path mapping rule)을 가지고 있는 것을 보실 수 있습니다.
이어서 (`react-router` 패키지에 의존하는 패키지인) `react-router-bootstrap` 또한 [`tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json) 파일 안에 경로 대응 규칙(Path mapping rule)을 가지고 있는 것을 보실 수 있습니다.
`/// <reference types=".." />` 에서는 경로 대응 규칙(Path mapping rule)이 동작하지 않기 때문에, Definitely Typed 패키지로에 의존할 때에는 임포트(import) 를 사용해야 합니다.
#### 전역적으로도 모듈로도 사용될 수 있는 패키지의 자료형 선언(Type declaration)은 어떻게 쓰나요?
타입스크립트 안내서(TypeScript Handbook)은 [선언(Declaration)을 쓰는 방법에 대한 전반적인 정보](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)와 [예시들](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)을 포함하고 있습니다. 이 내용에는 ES6 식의 모듈 문법을 사용할 수 있는 자료형 선언(Type declaration)을 만드는 방법과 객체를 전역에서 사용할 수 있도록 하는 방법이 포함되어 있습니다. [big.js 패키지의 자료형 선언(Type declaration)](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)이 실례입니다. 이 패키지는 웹 페이지의 스크립트 태그를 사용해 불러올 수 있으며, 또한 ES6 식의 임포트(Import) 구문을 사용해서 불러올 수도 있습니다.
타입스크립트 안내서(TypeScript Handbook)은 [선언(Declaration)을 쓰는 방법에 대한 전반적인 정보](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)와 [예시들](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)을 포함하고 있습니다. 이 내용에는 ES6 식의 모듈 문법을 사용할 수 있는 자료형 선언(Type declaration)을 만드는 방법과 객체를 전역에서 사용할 수 있도록 하는 방법이 포함되어 있습니다. [`big.js` 패키지의 자료형 선언(Type declaration)](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)이 실례입니다. 이 패키지는 웹 페이지의 스크립트 태그를 사용해 불러올 수 있으며, 또한 ES6 식의 임포트(Import) 구문을 사용해서 불러올 수도 있습니다.
여러분의 패키지가 임포트(Import) 구문을 사용했을 때와 전역적으로 불렀을 때를 테스트 해보고 싶다면, `test` 디렉토리를 추가하고 `YourLibraryName-global.test.ts` 그리고 `YourLibraryName-module.test.ts` 라는 이름으로 테스트 파일 두 개를 추가해주세요. **전역(Global)** 테스트 파일은 웹 페이지에서 전역적으로 사용될 때를 테스트하는 파일입니다. 이 파일에서는 임포트(Import) 구문을 사용하지 않아야 합니다. **모듈(Module)** 테스트 파일은 임포트(Import) 구문을 사용할 때를 테스트 하는 파일입니다. 만약 여러분의 `tsconfig.json` 파일이 `files` 필드(Field)를 가지고 있다면, 이 필드(Field)는 반드시 두 테스트 파일을 모두 포함해야 합니다. [이 방식을 사용하는 실례](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) 또한 big.js 패키지의 자료형 선언(Type declaration)에서 확인해보실 수 있습니다.
여러분의 패키지가 임포트(Import) 구문을 사용했을 때와 전역적으로 불렀을 때를 테스트 해보고 싶다면, `test` 디렉토리를 추가하고 `YourLibraryName-global.test.ts` 그리고 `YourLibraryName-module.test.ts` 라는 이름으로 테스트 파일 두 개를 추가해주세요. **전역(Global)** 테스트 파일은 웹 페이지에서 전역적으로 사용될 때를 테스트하는 파일입니다. 이 파일에서는 임포트(Import) 구문을 사용하지 않아야 합니다. **모듈(Module)** 테스트 파일은 임포트(Import) 구문을 사용할 때를 테스트 하는 파일입니다. 만약 여러분의 `tsconfig.json` 파일이 `files` 필드(Field)를 가지고 있다면, 이 필드(Field)는 반드시 두 테스트 파일을 모두 포함해야 합니다. [이 방식을 사용하는 실례](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) 또한 `big.js` 패키지의 자료형 선언(Type declaration)에서 확인해보실 수 있습니다.
각각의 테스트 파일에 모든 상황을 테스트할 필요는 없다는 걸 잊지마세요. 전역 테스트 파일에서는 전역적으로 사용될 때만 테스트하고, 모듈 테스트 파일에서 나머지 상황들을 모두 테스트 할 수 있으며, 그 반대의 경우도 괜찮습니다.

View File

@@ -17,10 +17,10 @@
- [Create a new package](#create-a-new-package)
- [Removing a package](#removing-a-package)
- [Running Tests](#running-tests)
- [\<my package>-tests.ts](#my-package-teststs)
- [`<my-package>-tests.ts`](#my-package-teststs)
- [Linter: `tslint.json`](#linter-tslintjson)
- [tsconfig.json](#tsconfigjson)
- [package.json](#packagejson)
- [`tsconfig.json`](#tsconfigjson)
- [`package.json`](#packagejson)
- [Common mistakes](#common-mistakes)
</details>
- [Definition Owners](#definition-owners)
@@ -176,12 +176,12 @@ Your package should have this structure:
| File | Purpose |
| ------------- | ------- |
| index.d.ts | This contains the typings for the package. |
| [\<my package>-tests.ts](#my-package-teststs) | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. |
| [tsconfig.json](#tsconfigjson) | This allows you to run `tsc` within the package. |
| [tslint.json](#linter-tslintjson) | Enables linting. |
| `index.d.ts` | This contains the typings for the package. |
| [`<my-package>-tests.ts`](#my-package-teststs) | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. |
| [`tsconfig.json`](#tsconfigjson) | This allows you to run `tsc` within the package. |
| [`tslint.json`](#linter-tslintjson) | Enables linting. |
Generate these by running `npx dts-gen --dt --name <my package> --template module` if you have npm ≥ 5.2.0, `npm install -g dts-gen` and `dts-gen --dt --name <my package> --template module` otherwise.
Generate these by running `npx dts-gen --dt --name <my-package> --template module` if you have npm ≥ 5.2.0, `npm install -g dts-gen` and `dts-gen --dt --name <my-package> --template module` otherwise.
See all options at [dts-gen](https://github.com/Microsoft/dts-gen).
If you have `.d.ts` files besides `index.d.ts`, make sure that they are referenced either in `index.d.ts` or the tests. If a file is neither tested nor referenced in `index.d.ts`, add it to a file named `OTHER_FILES.txt`. This file is a list of other files that need to be included in the typings package, one file per line.
@@ -197,7 +197,7 @@ When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration
You can remove it by running `npm run not-needed -- typingsPackageName asOfVersion [libraryName]`.
* `typingsPackageName`: This is the name of the directory to delete.
* `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version, and should be a version of `foo` on npm.
* `libraryName`: Name of npm package that replaces the Definitely Typed types. Usually this is identical to "typingsPackageName", in which case you can omit it.
* `libraryName`: Name of npm package that replaces the Definitely Typed types. Usually this is identical to `typingsPackageName`, in which case you can omit it.
Any other packages in Definitely Typed that referenced the deleted package should be updated to reference the bundled types.
You can get this list by looking at the errors from `npm run test-all`.
@@ -223,14 +223,14 @@ Test your changes by running `npm test <package to test>` where `<package to tes
This script uses [dtslint](https://github.com/microsoft/dtslint) to run the TypeScript compiler against your dts files.
#### \<my package>-tests.ts
#### `<my-package>-tests.ts`
There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.
There should be a `<my-package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my-package>`.
Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`
For example, this change to a function in a `.d.ts` file adding a new param to a function:
@@ -241,7 +241,7 @@ For example, this change to a function in a `.d.ts` file adding a new param to a
+ export function twoslash(body: string, config?: { version: string }): string
```
`<my package>-tests.ts`:
`<my-package>-tests.ts`:
```diff
import {twoslash} from "./"
@@ -278,13 +278,13 @@ The linter configuration file, `tslint.json` should contain `{ "extends": "dtsli
If for some reason some rule needs to be disabled, [disable it for that specific line](https://palantir.github.io/tslint/usage/rule-flags/#comment-flags-in-source-code:~:text=%2F%2F%20tslint%3Adisable%2Dnext%2Dline%3Arule1%20rule2%20rule3...%20%2D%20Disables%20the%20listed%20rules%20for%20the%20next%20line) using `// tslint:disable-next-line:[ruleName]` — not for the whole package, so that disabling can be reviewed. (There are some legacy lint configs that have additional contents, but these should not happen in new work.)
#### tsconfig.json
#### `tsconfig.json`
`tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
You may edit the `tsconfig.json` to add new test files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option.
#### package.json
#### `package.json`
Usually you won't need this.
DefinitelyTyped's package publisher creates a `package.json` for packages with no dependencies outside Definitely Typed.
@@ -533,9 +533,9 @@ Also, `/// <reference types=".." />` will not work with path mapping, so depende
#### How do I write definitions for packages that can be used globally and as a module?
The TypeScript handbook contains excellent [general information about writing definitions](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), and also [this example definition file](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) which shows how to create a definition using ES6-style module syntax, while also specifying objects made available to the global scope. This technique is demonstrated practically in the [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), which is a library that can be loaded globally via script tag on a web page, or imported via require or ES6-style imports.
The TypeScript handbook contains excellent [general information about writing definitions](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), and also [this example definition file](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) which shows how to create a definition using ES6-style module syntax, while also specifying objects made available to the global scope. This technique is demonstrated practically in the [definition for `big.js`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), which is a library that can be loaded globally via script tag on a web page, or imported via require or ES6-style imports.
To test how your definition can be used both when referenced globally or as an imported module, create a `test` folder, and place two test files in there. Name one `YourLibraryName-global.test.ts` and the other `YourLibraryName-module.test.ts`. The *global* test file should exercise the definition according to how it would be used in a script loaded on a web page where the library is available on the global scope - in this scenario you should not specify an import statement. The *module* test file should exercise the definition according to how it would be used when imported (including the `import` statement(s)). If you specify a `files` property in your `tsconfig.json` file, be sure to include both test files. A [practical example of this](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) is also available on the big.js definition.
To test how your definition can be used both when referenced globally or as an imported module, create a `test` folder, and place two test files in there. Name one `YourLibraryName-global.test.ts` and the other `YourLibraryName-module.test.ts`. The *global* test file should exercise the definition according to how it would be used in a script loaded on a web page where the library is available on the global scope - in this scenario you should not specify an import statement. The *module* test file should exercise the definition according to how it would be used when imported (including the `import` statement(s)). If you specify a `files` property in your `tsconfig.json` file, be sure to include both test files. A [practical example of this](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) is also available on the `big.js` definition.
Please note that it is not required to fully exercise the definition in each test file - it is sufficient to test only the globally-accessible elements on the global test file and fully exercise the definition in the module test file, or vice versa.

View File

@@ -18,10 +18,10 @@ Veja também o site [definitelytyped.org](http://definitelytyped.org), embora as
- [Crie um novo pacote](#crie-um-novo-pacote)
- [Removendo um pacote](#removendo-um-pacote)
- [Verificando](#verificando)
- [\<my package>-tests.ts](#my-package-teststs)
- [`<my-package>-tests.ts`](#my-package-teststs)
- [Linter: `tslint.json`](#linter-tslintjson)
- [tsconfig.json](#tsconfigjson)
- [package.json](#package.json)
- [`tsconfig.json`](#tsconfigjson)
- [`package.json`](#package.json)
- [Erros comuns](#erros-comuns)
</details>
- [Donos de definição](#donos-de-definição)
@@ -177,10 +177,10 @@ Seu pacote deve possuir a seguinte estrutura:
| Arquivo | Propósito |
| --- | --- |
| index.d.ts | Contém os tipos para o pacote. |
| [\<my package>-tests.ts](#my-package-teststs) | Contém código de exemplo que testa os tipos. Esse código *não* é executado, mas seus tipos são checados. |
| [tsconfig.json](#tsconfigjson) | Permite que você execute `tsc` dentro do pacote. |
| [tslint.json](#linter-tslintjson) | Habilita a análise do código pelo linter. |
| `index.d.ts` | Contém os tipos para o pacote. |
| [`<my-package>-tests.ts`](#my-package-teststs) | Contém código de exemplo que testa os tipos. Esse código *não* é executado, mas seus tipos são checados. |
| [`tsconfig.json`](#tsconfigjson) | Permite que você execute `tsc` dentro do pacote. |
| [`tslint.json`](#linter-tslintjson) | Habilita a análise do código pelo linter. |
Gere esses arquivos executando `npx dts-gen --dt --name nome-do-seu-pacote --template module` se você possuir a versão 5.2.0 ou mais recente do NPM ou `npm install -g dts-gen` e `dts-gen --dt --name nome-do-seu-pacote --template module` caso possua uma versão mais antiga.
Veja todas as opções em [dts-gen](https://github.com/Microsoft/dts-gen).
@@ -198,7 +198,7 @@ Quando um pacote [inclui](http://www.typescriptlang.org/docs/handbook/declaratio
Você pode removê-lo executando `npm run not-needed -- typingsPackageName asOfVersion [libraryName]`
- `typingsPackageName`: O nome do diretório a ser deletado.
- `asOfVersion`: Um esboço será publicado em `@types/foo` com essa versão. Deve ser maior do que qualquer versão atualmente publicada, e deve ser uma versão de `foo` no npm.
- `libraryName`: Nome do pacote no npm que substitui os tipos do Definitely Typed. Normalmente é idêntico ao "typingsPackageName", e nesse caso pode ser omitido.
- `libraryName`: Nome do pacote no npm que substitui os tipos do Definitely Typed. Normalmente é idêntico ao `typingsPackageName`, e nesse caso pode ser omitido.
Quaisquer outros pacotes no Definitely Typed que referenciavam o pacote deletado devem ser atualizados para referenciar os tipos inclusos pelo pacote.
Você pode obter esta lista olhando os erros do `npm test`.
@@ -224,14 +224,14 @@ Teste suas mudanças executando o comando `npm test nome-do-pacote` onde `nome-d
Este script usa o [dtslint](https://github.com/Microsoft/dtslint) para executar o compilador de TypeScript em seus arquivos dts.
#### \<my package>-tests.ts
#### `<my-package>-tests.ts`
Deve existir um arquivo `<my package>-tests.ts`, que é considerado seu arquivo de teste, junto a qualquer arquivo `*.ts` que ele importar.
Se você não encontrou nenhum arquivo de teste na pasta do módulo, crie um arquivo `<my package>-tests.ts`.
Deve existir um arquivo `<my-package>-tests.ts`, que é considerado seu arquivo de teste, junto a qualquer arquivo `*.ts` que ele importar.
Se você não encontrou nenhum arquivo de teste na pasta do módulo, crie um arquivo `<my-package>-tests.ts`.
Esses arquivos serão usados para validar a API exportada dos arquivos `*.d.ts` que são enviadas como `@types/seumódulo`.
Mudanças nos arquivos `*.d.ts` devem ser acompanhadas de mudanças nos arquivos `*.ts` que mostrem que a API sendo usada, para que ninguém acidentalmente "quebre" o código do qual você depende.
Se você não encontrou nenhum arquivo de teste na pasta do módulo, crie um arquivo `<my package>-tests.ts`.
Se você não encontrou nenhum arquivo de teste na pasta do módulo, crie um arquivo `<my-package>-tests.ts`.
Abaixo há um exemplo dessas mudanças em uma função em um arquivo `d.ts` adicionando um novo parâmetro à função:
@@ -242,7 +242,7 @@ Abaixo há um exemplo dessas mudanças em uma função em um arquivo `d.ts` adic
+ export function twoslash(body: string, config?: { version: string }): string
```
`<my package>-tests.ts`:
`<my-package>-tests.ts`:
```diff
import {twoslash} from "./"
@@ -278,13 +278,13 @@ The linter configuration file, `tslint.json` should contain `{ "extends": "dtsli
If for some reason some rule needs to be disabled, [disable it for that specific line](https://palantir.github.io/tslint/usage/rule-flags/#comment-flags-in-source-code:~:text=%2F%2F%20tslint%3Adisable%2Dnext%2Dline%3Arule1%20rule2%20rule3...%20%2D%20Disables%20the%20listed%20rules%20for%20the%20next%20line) using `// tslint:disable-next-line:[ruleName]` — not for the whole package, so that disabling can be reviewed. (There are some legacy lint configs that have additional contents, but these should not happen in new work.)
#### tsconfig.json
#### `tsconfig.json`
`tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
Você pode editar o `tsconfig.json` para adicionar novos arquivos de teste, para adicionar `"target": "es6"` (necessário para funções assíncronas), para adicionar a `"lib"`, ou para adicionar a opção `"jsx"` do compilador.
#### package.json
#### `package.json`
Geralmente você não precisa disso.
O distribuidor de pacotes do Definitely Typed cria um `package.json` para pacotes sem dependências fora do Definitely Typed.
@@ -526,9 +526,9 @@ Provisoriamente, o `react-router-bootstrap` (que depende do `react-router`) tamb
#### Como eu crio definições para pacotes que podem ser usados globalmente e como um módulo?
O manual do TypeScript contém excelentes [informações gerais sobre criar definições](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), e também [este arquivo de definição de exemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) que mostra como criar uma definição usando a sintaxe de módulo no estilo ES6, enquanto também especifica os objetos que tornaram-se disponíveis ao escopo global. Essa técnica é demonstrada de forma prática na [definição da big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), que é uma biblioteca que pode ser carregada globalmente via tags de script numa página da web, ou importada via require ou via imports no estilo do ES6.
O manual do TypeScript contém excelentes [informações gerais sobre criar definições](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), e também [este arquivo de definição de exemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) que mostra como criar uma definição usando a sintaxe de módulo no estilo ES6, enquanto também especifica os objetos que tornaram-se disponíveis ao escopo global. Essa técnica é demonstrada de forma prática na [definição da `big.js`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), que é uma biblioteca que pode ser carregada globalmente via tags de script numa página da web, ou importada via require ou via imports no estilo do ES6.
Para testar como sua definição pode ser usada tanto quando referenciada globalmente quanto como um módulo importável, crie uma pasta `test`, e coloque dois arquivos de teste nela. Chame um de `NomeDaSuaBiblioteca-global.test.ts` e o outro de `NomeDaSuaBiblioteca-module.test.ts`. O arquivo de teste *global* deve exercer a definição de acordo com como ele seria usado num script carregado numa página da web onde a biblioteca está disponível no escopo global - nesse cenário você não deve especificar uma declaração de importação. O arquivo de teste *module* deve exercer a definição de acordo com como ele seria usado quando importado (incluindo a(s) definição(ões) de `import`). Se Você especificar uma propriedade `files` no seu arquivo `tsconfig.json`, tenha certeza de incluir ambos os arquivos de teste. Um [exemplo prático de como fazer isso](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) também está disponível na definição da big.js.
Para testar como sua definição pode ser usada tanto quando referenciada globalmente quanto como um módulo importável, crie uma pasta `test`, e coloque dois arquivos de teste nela. Chame um de `NomeDaSuaBiblioteca-global.test.ts` e o outro de `NomeDaSuaBiblioteca-module.test.ts`. O arquivo de teste *global* deve exercer a definição de acordo com como ele seria usado num script carregado numa página da web onde a biblioteca está disponível no escopo global - nesse cenário você não deve especificar uma declaração de importação. O arquivo de teste *module* deve exercer a definição de acordo com como ele seria usado quando importado (incluindo a(s) definição(ões) de `import`). Se Você especificar uma propriedade `files` no seu arquivo `tsconfig.json`, tenha certeza de incluir ambos os arquivos de teste. Um [exemplo prático de como fazer isso](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) também está disponível na definição da `big.js`.
Por favor note que isso não é obrigatório para exercer completamente a definição em cada arquivo de teste - é suficiente para testar apenas os elementos accessíveis globalmente no arquivo de teste global e exercer a definição no arquivo de teste do módulo, ou vice versa.

View File

@@ -20,10 +20,10 @@ _Вы также можете прочитать этот README на [англ
- [Создание нового пакета](#создание-нового-пакета)
- [Удаление пакета](#удаление-пакета)
- [Проверка](#проверка)
- [\<my package>-tests.ts](#my-package-teststs)
- [`<my-package>-tests.ts`](#my-package-teststs)
- [Linter: `tslint.json`](#linter-tslintjson)
- [tsconfig.json](#tsconfigjson)
- [package.json](#packagejson)
- [`tsconfig.json`](#tsconfigjson)
- [`package.json`](#packagejson)
- [Распространенные ошибки](#распространенные-ошибки)
</details>
- [Definition Owners](#definition-owners)
@@ -187,12 +187,12 @@ Definitely Typed работает только благодаря вкладу
| Файл | Назначение |
| ------------- | ---------------------------------------------------------------------------------------------------- |
| index.d.ts | Содержит типизацию для пакета. |
| [\<my package>-tests.ts](#my-package-teststs) | Содержит пример кода, который проверяет типизацию. Этот код _не_ запускается, но он проверен на тип. |
| [tsconfig.json](#tsconfigjson) | Позволяет вам запускать `tsc` внутри пакета. |
| [tslint.json](#linter-tslintjson) | Включает linting. |
| `index.d.ts` | Содержит типизацию для пакета. |
| [`<my-package>-tests.ts`](#my-package-teststs) | Содержит пример кода, который проверяет типизацию. Этот код _не_ запускается, но он проверен на тип. |
| [`tsconfig.json`](#tsconfigjson) | Позволяет вам запускать `tsc` внутри пакета. |
| [`tslint.json`](#linter-tslintjson) | Включает linting. |
Создайте их, запустив `npx dts-gen --dt --name <my package> --template module` если у вас npm ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name <my package> --template module` в противном случае.
Создайте их, запустив `npx dts-gen --dt --name <my-package> --template module` если у вас npm ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name <my-package> --template module` в противном случае.
Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen).
Члены группы Definitely Typed регулярно следят за новыми PR, но имейте в виду, что количество других PR может замедлить ход событий.
@@ -207,7 +207,7 @@ Definitely Typed работает только благодаря вкладу
- `typingsPackageName`: название директории, который нужно удалить.
- `asOfVersion`: заглушка будет опубликована в `@types/foo` с этой версией. Должна быть выше, чем любая опубликованная на данный момент версия
- `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично "typingsPackageName".)
- `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично `typingsPackageName`.)
Любые другие пакеты в Definitely Typed которые ссылаются на удаленный пакет, должны быть обновлены для ссылки на связанные типы. Для этого добавьте в [`package.json`](#packagejson) ссыклу `"dependencies": { "foo": "x.y.z" }`.
@@ -219,14 +219,14 @@ Definitely Typed работает только благодаря вкладу
Этот скрипт использует [dtslint](https://github.com/Microsoft/dtslint) для запуска компилятора TypeScript на ваших dts файлах.
#### \<my package>-tests.ts
#### `<my-package>-tests.ts`
There should be a `<my package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my package>`.
There should be a `<my-package>-tests.ts` file, which is considered your test file, along with any `*.ts` files it imports.
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`.
These files are used to validate the API exported from the `*.d.ts` files which are shipped as `@types/<my-package>`.
Changes to the `*.d.ts` files should include a corresponding `*.ts` file change which shows the API being used, so that someone doesn't accidentally break code you depend on.
If you don't see any test files in the module's folder, create a `<my package>-tests.ts`
If you don't see any test files in the module's folder, create a `<my-package>-tests.ts`
For example, this change to a function in a `.d.ts` file adding a new param to a function:
@@ -237,7 +237,7 @@ For example, this change to a function in a `.d.ts` file adding a new param to a
+ export function twoslash(body: string, config?: { version: string }): string
```
`<my package>-tests.ts`:
`<my-package>-tests.ts`:
```diff
import {twoslash} from "./"
@@ -274,13 +274,13 @@ The linter configuration file, `tslint.json` should contain `{ "extends": "dtsli
If for some reason some rule needs to be disabled, [disable it for that specific line](https://palantir.github.io/tslint/usage/rule-flags/#comment-flags-in-source-code:~:text=%2F%2F%20tslint%3Adisable%2Dnext%2Dline%3Arule1%20rule2%20rule3...%20%2D%20Disables%20the%20listed%20rules%20for%20the%20next%20line) using `// tslint:disable-next-line:[ruleName]` — not for the whole package, so that disabling can be reviewed. (There are some legacy lint configs that have additional contents, but these should not happen in new work.)
#### tsconfig.json
#### `tsconfig.json`
`tsconfig.json` should have `noImplicitAny`, `noImplicitThis`, `strictNullChecks`, and `strictFunctionTypes` set to `true`.
Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`.
#### package.json
#### `package.json`
Обычно вам это не нужно. При публикации пакета мы обычно автоматически создаем `package.json`.
`package.json` может быть включен для определения зависимостей. Вот [пример](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
@@ -402,15 +402,15 @@ Once a week the Definition Owners are synced to the file [.github/CODEOWNERS](ht
Если в Definitely Typed есть другие пакеты, несовместимые с новой версией, вам нужно будет добавить сопоставления путей к старой версии. Вам также нужно будет сделать это для пакетов в зависимости от пакетов в зависимости от старой версии.
Например, `react-router` зависит от `history@2`, поэтому [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) есть сопоставление пути с `"history": [ "history/v2" ]`;
транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [`tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Также, `/// <reference types=".." />` не будет работать с отображением пути, поэтому зависимости должны использовать `import`.
#### Как мне написать определения для пакетов, которые могут использоваться и глобально и в качестве модуля?
Руководство TypeScript содержит отличную [общую информацию о написании определений](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), а также [этот пример файла определения](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) , в котором показано, как создать определение с использованием синтаксиса модуля в стиле ES6, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6.
Руководство TypeScript содержит отличную [общую информацию о написании определений](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), а также [этот пример файла определения](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) , в котором показано, как создать определение с использованием синтаксиса модуля в стиле ES6, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for `big.js`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6.
Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. _Глобальный_ тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл _модуля_ должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении big.js.
Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. _Глобальный_ тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл _модуля_ должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении `big.js`.
Обратите внимание, что не требуется полностью использовать определение в каждом тестовом файле - достаточно протестировать только глобально доступные элементы в глобальном тестовом файле и полностью выполнить определение в тестовом файле модуля, или наоборот.