Revert README changes (#48958)

Revert the erroneously-merged changes to the READMEs, and instead just
leave some minor edits in the main `README.md`.
This commit is contained in:
Eli Barzilay
2020-10-20 14:09:09 -04:00
committed by GitHub
parent 63695e57d0
commit 010b39c203
6 changed files with 989 additions and 964 deletions

View File

@@ -1,35 +1,35 @@
# Definitely Typed
> 这是一个 _高质量_ 的 TypeScript 类型定义的仓库。
> 这是一个 *高质量* 的 TypeScript 类型定义的仓库。
也可以去看 [definitelytyped.org](http://definitelytyped.org) 这个网站,尽管这个 README 里的信息更新。
_你可以去看其他语言的 README[英语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md)[西班牙语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)[韩语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)[俄罗斯语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)_
*你可以去看其他语言的 README[英语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md)[西班牙语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)[韩语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)[俄罗斯语](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)*
_[管理员手册](./docs/admin.md)_
*[管理员手册](./docs/admin.md)*
## 目录
- [当前状态](#当前状态)
- [我该如何贡献?](#我该如何贡献)
- [测试](#测试)
- [发起一个 pull request](#发起一个-pull-request)
- [编辑一个现有包](#编辑一个现有包)
- [创建一个新的包](#创建一个新的包)
- [常见错误](#常见错误)
- [删除一个包](#删除一个包)
- [Linter](#linter)
- [FAQ](#faq)
* [当前状态](#当前状态)
* [我该如何贡献?](#我该如何贡献)
* [测试](#测试)
* [发起一个 pull request](#发起一个-pull-request)
* [编辑一个现有包](#编辑一个现有包)
* [创建一个新的包](#创建一个新的包)
* [常见错误](#常见错误)
* [删除一个包](#删除一个包)
* [Linter](#linter)
* [FAQ](#faq)
## 当前状态
这个部分会跟踪仓库和发布过程的运行状况。
这可能会对在 PRs 和包中遇到任何问题的贡献者有所帮助。
- 最近的构建都具有完善的 [类型标注](https://github.com/Microsoft/dtslint)[![Build Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.DefinitelyTyped?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=1&branchName=master)
- 所有的包基于 typescript@next 版本都有完善的类型标注:[![Build status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/Nightly%20dtslint)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=8)
- 所有的包都会在 1 小时内 [发布到 npm](https://github.com/Microsoft/types-publisher): [![Publish Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.types-publisher-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=5&branchName=master)
- [typescript-bot](https://github.com/typescript-bot) 在 Definitely Typed 一直处于活跃状态 [![Activity Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.typescript-bot-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=6&branchName=master)
* 最近的构建都具有完善的 [类型标注](https://github.com/Microsoft/dtslint)[![Build Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.DefinitelyTyped?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=1&branchName=master)
* 所有的包基于 typescript@next 版本都有完善的类型标注:[![Build status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/Nightly%20dtslint)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=8)
* 所有的包都会在1小时内 [发布到 npm](https://github.com/Microsoft/types-publisher): [![Publish Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.types-publisher-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=5&branchName=master)
* [typescript-bot](https://github.com/typescript-bot) 在 Definitely Typed 一直处于活跃状态 [![Activity Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.typescript-bot-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=6&branchName=master)
如果这里面的任何内容出现问题或者失败的情况,请在 [the Definitely Typed channel on the TypeScript Community Discord server](https://discord.gg/typescript) 提出问题。
@@ -61,41 +61,41 @@ npm install --save-dev @types/node
Definitely Typed 仅在小于 2 年的 TypeScript 版本上测试软件包。当前已测试 3.2 及更高版本。如果您使用的是 TypeScript 2.0 到 3.1,仍然可以尝试安装 @types 软件包,大多数软件包都不使用 TypeScript 的新特性。但是不能保证它们会起作用,这是支持窗口:
| Version | Released | End of Support |
| ------- | -------------- | -------------- |
| 2.8 | March 2018 | March 2020 |
| 2.9 | May 2018 | May 2020 |
| 3.0 | July 2018 | July 2020 |
| 3.1 | September 2018 | September 2020 |
| 3.2 | November 2018 | November 2020 |
| 3.3 | January 2019 | January 2021 |
| 3.4 | March 2019 | March 2021 |
| 3.5 | May 2019 | May 2021 |
| 3.6 | August 2019 | August 2021 |
| 3.7 | November 2019 | November 2021 |
| 3.8 | February 2020 | February 2022 |
| 3.9 | May 2020 | May 2022 |
| 4.0 | August 2020 | August 2022 |
Version | Released | End of Support
-- | -- | --
2.8 | March 2018 | March 2020
2.9 | May 2018 | May 2020
3.0 | July 2018 | July 2020
3.1 | September 2018 | September 2020
3.2 | November 2018 | November 2020
3.3 | January 2019 | January 2021
3.4 | March 2019 | March 2021
3.5 | May 2019 | May 2021
3.6 | August 2019 | August 2021
3.7 | November 2019 | November 2021
3.8 | February 2020 | February 2022
3.9 | May 2020 | May 2022
4.0 | August 2020 | August 2022
`@types` 软件包具有它们明确支持的 TypeScript 版本的标记,因此通常可以获取早于 2 年窗口的较早版本的软件包。例如,如果运行 `npm dist-tags @types/react`,您将看到 TypeScript 2.5 可以将类型用于 react@16.0,而 TypeScript 2.6 和 2.7 可以将类型用于 react@16.4
| Tag | Version |
| ------ | ------- |
| latest | 16.9.23 |
| ts2.0 | 15.0.1 |
| ... | ... |
| ts2.5 | 16.0.36 |
| ts2.6 | 16.4.7 |
| ts2.7 | 16.4.7 |
| ... | ... |
|Tag | Version|
|----|---------|
|latest| 16.9.23|
|ts2.0| 15.0.1|
| ... | ... |
|ts2.5| 16.0.36|
|ts2.6| 16.4.7|
|ts2.7| 16.4.7|
| ... | ... |
#### TypeScript 1.\*
#### TypeScript 1.*
这些可以被 TypeScript 1.0 使用。
- 从该仓库的 `master` 分支手动下载并将其放入您的项目中
- ~~[Typings](https://github.com/typings/typings)~~ (使用首选替代方案typings 已经被弃用)
- ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (使用首选替代方案, nuget DT 类型发布已关闭)
* 从该仓库的 `master` 分支手动下载并将其放入您的项目中
* ~~[Typings](https://github.com/typings/typings)~~ (使用首选替代方案typings 已经被弃用)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (使用首选替代方案, nuget DT 类型发布已关闭)
你可能需要手动添加 [引用](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)。
@@ -137,20 +137,20 @@ Definitely Typed 仅在小于 2 年的 TypeScript 版本上测试软件包。当
#### 编辑一个现有包
- `cd types/my-package-to-edit`
- 作出修改之后,记得新增测试。
如果你进行了重大修改,不要忘记 [更新主版本](#if-a-library-is-updated-to-a-new-major-version-with-breaking-changes-how-should-i-update-its-type-declaration-package)
- 你可能还想将自己添加到包头部的 "Definitions by" 部分。
- 这会导致一旦有人对该包发起 PR 或者 issue都会通知你通过你的 GitHub 用户名)。
- 通过将您的名字添加到行尾来执行此操作,比如 `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- 或者如果有多人,它也可以是多行的
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
- 如果这里有 `tslint.json` 文件,就运行 `npm run lint package-name`。否则,在包目录里运行 `tsc`.
* `cd types/my-package-to-edit`
* 作出修改之后,记得新增测试。
如果你进行了重大修改,不要忘记 [更新主版本](#if-a-library-is-updated-to-a-new-major-version-with-breaking-changes-how-should-i-update-its-type-declaration-package)
* 你可能还想将自己添加到包头部的 "Definitions by" 部分。
- 这会导致一旦有人对该包发起 PR 或者 issue都会通知你通过你的 GitHub 用户名)。
- 通过将您的名字添加到行尾来执行此操作,比如 `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- 或者如果有多人,它也可以是多行的
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* 如果这里有 `tslint.json` 文件,就运行 `npm run lint package-name`。否则,在包目录里运行 `tsc`.
当你对现有的包发起 PR 的时候,请确保 `dt-bot` 会通知以前的作者。
如果没有,你可以在与 PR 关联的评论中手动去 @ 他们。
@@ -165,12 +165,12 @@ Definitely Typed 仅在小于 2 年的 TypeScript 版本上测试软件包。当
你的包应该具有这样的结构:
| 文件名 | 目的 |
| ------------- | ---------------------------------------------------------------------------- |
| index.d.ts | 这里包含了包的类型声明。 |
| foo-tests.ts | 这里包含了测试类型的示例代码,此代码 **不会** 运行,但是它需要通过类型检查。 |
| tsconfig.json | 这里允许你在包里运行 `tsc`. |
| tslint.json | 启用 linting. |
| 文件名 | 目的 |
| --- | --- |
| index.d.ts | 这里包含了包的类型声明。 |
| foo-tests.ts | 这里包含了测试类型的示例代码,此代码 **不会** 运行,但是它需要通过类型检查。 |
| tsconfig.json | 这里允许你在包里运行 `tsc`. |
| tslint.json | 启用 linting. |
如果你的 npm ≥ 5.2.0,运行 `npx dts-gen --dt --name my-package-name --template module` 来生成这些文件,否则就运行 `npm install -g dts-gen` 和 `dts-gen --dt --name my-package-name --template module`.
可以在 [dts-gen](https://github.com/Microsoft/dts-gen) 查看所有的选项。
@@ -183,25 +183,25 @@ Definitely Typed 的成员会定期查看新的 PRs但是请记住当有许
#### 常见错误
- 首先,请遵循 [手册](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html) 的建议。
- 格式化:使用 4 个空格。 该仓库已经设置了 prettier因此你只需要运行 `npm run prettier -- --write path/to/package/**/*.ts`. [使用断言时](https://github.com/SamVerschueren/tsd#assertions),添加 `// prettier-ignore` 将这几行标记为不需要格式化的代码:
* 首先,请遵循 [手册](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html) 的建议。
* 格式化:使用4个空格。 该仓库已经设置了 prettier因此你只需要运行 `npm run prettier -- --write path/to/package/**/*.ts`. [使用断言时](https://github.com/SamVerschueren/tsd#assertions),添加 `// prettier-ignore` 将这几行标记为不需要格式化的代码:
```tsx
// prettier-ignore
const incompleteThemeColorModes: Theme = { colors: { modes: { papaya: { // $ExpectError
```
- `function sum(nums: number[]): number`: 如果函数没有写入的参数,请使用 `ReadonlyArray`.
- `interface Foo { new(): Foo; }`:
* `function sum(nums: number[]): number`: 如果函数没有写入的参数,请使用 `ReadonlyArray`.
* `interface Foo { new(): Foo; }`:
这定义了一个可实例化的类型,你可能需要的是 `declare class Foo { constructor(); }`.
- `const Class: { new(): IClass; }`:
* `const Class: { new(): IClass; }`:
更推荐使用类声明 `class Class { constructor(); }`,而不是生成一个可实例化的类型。
- `getMeAT<T>(): T`:
* `getMeAT<T>(): T`:
如果类型参数没有出现在函数的参数中,那么实际上你不需要这个泛型函数,你只是用了一个伪装的类型断言。
这种情况下最好使用真实的类型断言,类似这样,`getMeAT() as number`.
类型参数可接受的示例:`function id<T>(value: T): T;`.
类型参数不可接受的示例:`function parseJson<T>(json: string): T;`.
有一个例外:`new Map<string, number>()` 是 OK 的。
- 使用 `Function` 和 `Object` 的类型基本上不是一个好方法。在 99% 的情况你可以去指定一个更具体的类型。比如,对于 [Function](http://www.typescriptlang.org/docs/handbook/functions.html#function-types),可以使用 `(x: number) => number`,对于 `Object` 可以使用 `{ x: number, y: number }`. 对于不确定的类型,你需要使用 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 而不是 `Object`. 只有当它类型确定且是某个对象的时候,使用 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), 而不是 `Object` 或 `{ [key: string]: any }`.
- `var foo: string | any`:
* 使用 `Function` 和 `Object` 的类型基本上不是一个好方法。在 99% 的情况你可以去指定一个更具体的类型。比如,对于 [Function](http://www.typescriptlang.org/docs/handbook/functions.html#function-types),可以使用 `(x: number) => number`,对于 `Object` 可以使用 `{ x: number, y: number }`. 对于不确定的类型,你需要使用 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 而不是 `Object`. 只有当它类型确定且是某个对象的时候,使用 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), 而不是 `Object` 或 `{ [key: string]: any }`.
* `var foo: string | any`:
如果在联合类型中使用 `any`, 则结果始终为 `any`. 因此,即便类型中的 `string` 部分看起来很有用,但实际上在类型检查方面与 `any` 没有什么区别。根据你的意图,可以选择 `any`, `string`, 或 `string | object`.
#### 删除一个包
@@ -209,10 +209,9 @@ Definitely Typed 的成员会定期查看新的 PRs但是请记住当有许
当一个包 [捆绑](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) 了自己的类型时,应该从 Definitely Typed 中删除类型避免被混淆。
你可以运行以下命令来删除它 `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
- `typingsPackageName`: 这是你要删除的目录名字.
- `asOfVersion`: 将使用此版本将存根发布到 `@types/foo`. 版本号应该高于当前发布的任何版本,并且应该是 npm 上的 `foo` 版本
- `libraryName`: 替换 Definitely Typed 中类型的 npm 的包名。通常这与 "typingsPackageName" 相同,这种情况下你可以忽略它。
- `typingsPackageName`: 这是你要删除的目录名字.
- `asOfVersion`: 将使用此版本将存根发布到 `@types/foo`. 版本号应该高于当前发布的任何版本,并且应该是 npm 上的 `foo` 版本。
- `libraryName`: 替换 Definitely Typed 中类型的 npm 的包名。通常这与 "typingsPackageName" 相同,这种情况下你可以忽略它
Definitely Typed 中其他引用了删除包的任何包,都需要去更新去引用新的捆绑类型。
你可以查看 `npm run test` 中的错误来获得此列表。
@@ -221,10 +220,10 @@ Definitely Typed 中其他引用了删除包的任何包,都需要去更新去
```json
{
"private": true,
"dependencies": {
"foo": "^2.6.0"
}
"private": true,
"dependencies": {
"foo": "^2.6.0"
}
}
```
@@ -235,7 +234,6 @@ Definitely Typed 中其他引用了删除包的任何包,都需要去更新去
#### Linter
所有新的包都必须通过 lint. 需要添加 `tslint.json` 文件去 lint 这个包。
```js
{
"extends": "dtslint/dt.json"
@@ -243,7 +241,6 @@ Definitely Typed 中其他引用了删除包的任何包,都需要去更新去
```
这应该是一个已完成项目里 `tslint.json` 文件的唯一内容。如果这个文件关闭了某些规则,是因为它还未完全修复。例如:
```js
{
"extends": "dtslint/dt.json",
@@ -263,7 +260,7 @@ Definitely Typed 中其他引用了删除包的任何包,都需要去更新去
f(1);
// $ExpectError
f('one');
f("one");
```
你可以查阅 [dtslint](https://github.com/Microsoft/dtslint#write-tests) 的 readme 去看更多详细信息。
@@ -273,6 +270,7 @@ f('one');
通过运行 `npm run lint package-name` 去测试你的改动,其中 `package-name` 是你的包名。
这个脚本使用了 [dtslint](https://github.com/Microsoft/dtslint).
## FAQ
#### 这个仓库和 NPM 上的 `@types` 包究竟有什么关系?
@@ -331,9 +329,8 @@ Definitely Typed 包的发布者会为在 Definitely Typed 之外没有依赖的
使用 `import foo = require("foo");` 语法导入模块更合适。
不过,如果你想使用像 `import foo from "foo";` 这样的默认导入,你有两个选择:
- 你可以使用 [`--allowSyntheticDefaultImports` 的编译器选项](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) 取决于你的模块运行是支持 non-ECMAScript 模块的互操作方案 ,即默认导入是否适用于你的环境(例如 Webpack, SystemJS, esm)。
- 你可以使用 [`--esModuleInterop` 的编译器选项](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop),如果你想使用 TypeScript 去处理 non-ECMAScript 的操作(从 Typescript 2.7 版本开始)。
- 你可以使用 [`--allowSyntheticDefaultImports` 的编译器选项](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) 取决于你的模块运行是支持 non-ECMAScript 模块的互操作方案 ,即默认导入是否适用于你的环境(例如 Webpack, SystemJS, esm
- 你可以使用 [`--esModuleInterop` 的编译器选项](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop),如果你想使用 TypeScript 去处理 non-ECMAScript 的操作(从 Typescript 2.7 版本开始)。
#### 一个包使用了 `export =`, 但是我更喜欢使用默认导入。我可以将 `export =` 改为 `export default` 吗?
@@ -367,7 +364,6 @@ Definitely Typed 包的发布者会为在 Definitely Typed 之外没有依赖的
2. 在你的类型目录中创建一个在 `typesVersions` 字段中提到的子目录(在本例中为 `ts3.1/`),并为这个新版本添加特定的类型和测试。你不需要在 `ts3.1/` 目录中任何一个文件添加传统的定义头部。
3. 将 `ts3.1/tsconfig.json` 中 `baseUrl` 和 `typeRoots` 选项设置成正确的路径,它们应该如下所示:
```json
{
"compilerOptions": {
@@ -411,9 +407,9 @@ _注意本节中的讨论假定你熟悉 [语义版本控制](https://semver.
以下是一些常见的原因,是按照给库的用户带来不便的顺序排序的。
只有最后一种情况通常是有问题的。
- 如上所示,类型定义包的补丁版本与库包的补丁版本是无关的。这允许 Definitely Typed 安全地更新同一主/次版本的类型声明。
- 如果要更新包去获取新的功能,请不要忘记更新版本号以与该版本的库对齐。
- 类型定义包的更新落后于库的原因通常是因为库用户而不是维护者,他们在发布新特性从而更新了库的版本。因此,在愿意帮忙的社区成员发送 PR 去更新新的库版本对应的类型声明包之前,可能会有几天,几周甚至几个月的滞后。如果你深受此影响,你可以成为你想改变的,你可以去成为乐于助人的社区成员!
* 如上所示,类型定义包的补丁版本与库包的补丁版本是无关的。这允许 Definitely Typed 安全地更新同一主/次版本的类型声明。
* 如果要更新包去获取新的功能,请不要忘记更新版本号以与该版本的库对齐。
* 类型定义包的更新落后于库的原因通常是因为库用户而不是维护者,他们在发布新特性从而更新了库的版本。因此,在愿意帮忙的社区成员发送 PR 去更新新的库版本对应的类型声明包之前,可能会有几天,几周甚至几个月的滞后。如果你深受此影响,你可以成为你想改变的,你可以去成为乐于助人的社区成员!
:exclamation: 如果你想更新库的类型声明,请记住始终要在 `index.d.ts` 文件的第一行设置 `major.minor` 的版本号去匹配你正在记录的库版本! :exclamation:
@@ -443,10 +439,13 @@ _注意本节中的讨论假定你熟悉 [语义版本控制](https://semver.
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": ["history/v2"]
}
"history": [ "history/v2" ]
},
},
"files": ["index.d.ts", "history-tests.ts"]
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
@@ -462,7 +461,7 @@ _注意本节中的讨论假定你熟悉 [语义版本控制](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 风格的风格导入。
要测试你的类型定义是否能全局引用或者作为模块导入,请创建一个 `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)。
请注意,不需要在每个测试文件中完全执行定义 - 只需要在全局测试文件中测试全局可访问元素并在模块测试文件中完全执行定义,反之亦然。
@@ -474,8 +473,8 @@ TypeScript 手册包含了优秀的 [关于编写类型定义的概括信息](ht
```json
{
"paths": {
"@foo/*": ["foo__*"]
"paths":{
"@foo/*": ["foo__*"]
}
}
```

View File

@@ -4,10 +4,12 @@
Vea también el sitio web [definitelytyped.org](http://definitelytyped.org), aunque la información en este README está más actualizada.
## ¿Qué son los `declaration files`?
Vea el [Manual de TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## ¿Cómo los obtengo?
### npm
@@ -34,43 +36,44 @@ Definitely Typed solamente prueba paquetes en versiones de TypeScript que son me
Actualmente, las versiones 3.2 y posteriores están siendo probadas. Si estas usando TypeScript 2.0 a 3.1, puedes intentar instalando paquetes `@types` &mdash; la mayoría de los paquetes no usan los beneficios de Typescript más nuevos. No hay garantía de que funcionen.
Versiones soportadas:
| Versión | Liberado | Fin de soporte |
| ------- | --------------- | --------------- |
| 2.8 | Marzo 2018 | Marzo 2020 |
| 2.9 | Mayo 2018 | Mayo 2020 |
| 3.0 | Julio 2018 | Julio 2020 |
| 3.1 | Septiembre 2018 | Septiembre 2020 |
| 3.2 | Noviembre 2018 | Noviembre 2020 |
| 3.3 | Enero 2019 | Enero 2020 |
| 3.4 | Marzo 2019 | Marzo 2021 |
| 3.5 | Mayo 2019 | Mayo 2021 |
| 3.6 | Agosto 2019 | Agosto 2021 |
| 3.7 | Noviembre 2019 | Noviembre 2021 |
| 3.8 | Febrero 2020 | Febrero 2022 |
| 3.9 | Mayo 2020 | Mayo 2022 |
| 4.0 | Agosto 2020 | Agosto 2022 |
Versión | Liberado | Fin de soporte
-- | -- | --
2.8 | Marzo 2018 | Marzo 2020
2.9 | Mayo 2018 | Mayo 2020
3.0 | Julio 2018 | Julio 2020
3.1 | Septiembre 2018 | Septiembre 2020
3.2 | Noviembre 2018 | Noviembre 2020
3.3 | Enero 2019 | Enero 2020
3.4 | Marzo 2019 | Marzo 2021
3.5 | Mayo 2019 | Mayo 2021
3.6 | Agosto 2019 | Agosto 2021
3.7 | Noviembre 2019 | Noviembre 2021
3.8 | Febrero 2020 | Febrero 2022
3.9 | Mayo 2020 | Mayo 2022
4.0 | Agosto 2020 | Agosto 2022
Los paquetes `@types` tienen etiquetas para las versiones de Typescript que explícitamente soportan, usualmente puedes obtener versiones más viejas de los paquetes anteriores a 2 años.
Por ejemplo, si ejecutas `npm dist-tags @types/react`, observaras que Typescript 2.5 puede usar types para react@16.0, a su vez, Typescript 2.6 y 2.7 pueden usar types para react@16.4.
| Etiqueta | Versión |
| -------- | ------- |
| latest | 16.9.23 |
| ts2.0 | 15.0.1 |
| ... | ... |
| ts2.5 | 16.0.36 |
| ts2.6 | 16.4.7 |
| ts2.7 | 16.4.7 |
| ... | ... |
|Etiqueta | Versión|
|----|---------|
|latest| 16.9.23|
|ts2.0| 15.0.1|
| ... | ... |
|ts2.5| 16.0.36|
|ts2.6| 16.4.7|
|ts2.7| 16.4.7|
| ... | ... |
#### Typescript 1.\*
#### Typescript 1.*
- Descárguelo manualmente desde la `master` branch de este repositorio
- [Typings](https://github.com/typings/typings)~~ (use las alternativas preferidas, typings es obsoleto)
- ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada)
* Descárguelo manualmente desde la `master` branch de este repositorio
* [Typings](https://github.com/typings/typings)~~ (use las alternativas preferidas, typings es obsoleto)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada)
Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## ¿Cómo puedo contribuir?
¡Definitely Typed solo trabaja gracias a contribuidores como tú!
@@ -84,6 +87,7 @@ Antes de compartir tu mejora con el mundo, úselo usted mismo.
Para agregar nuevas funciones puedes usar el [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html).
También puedes editar directamente los types en `node_modules/@types/foo/index.d.ts`, o copiarlos de ahí y seguir los pasos explicados a continuación.
#### Prueba un nuevo paquete
Añade a tu `tsconfig.json`:
@@ -96,37 +100,40 @@ Añade a tu `tsconfig.json`:
(También puedes usar `src/types`.)
Crea un `types/foo/index.d.ts` que contenga declaraciones del módulo "foo".
Ahora deberías poder importar desde `"foo"` a tu código y te enviara a un nuevo tipo de definición.
Entonces compila _y_ ejecuta el código para asegurarte que el tipo de definición en realidad corresponde a lo que suceda en el momento de la ejecución.
Entonces compila *y* ejecuta el código para asegurarte que el tipo de definición en realidad corresponde a lo que suceda en el momento de la ejecución.
Una vez que hayas probado tus definiciones con el código real, haz un [PR](#make-a-pull-request)
luego sigue las instrucciones para [editar un paquete existente](#edit-an-existing-package) o
[crear un nuevo paquete](#create-a-new-package).
### Haz un pull request
Una vez que hayas probado tu paquete, podrás compartirlo en Definitely Typed.
Primero, haz un [fork](https://guides.github.com/activities/forking/) en este repositorio, instala [node](https://nodejs.org/), y luego ejecuta la `npm install`.
#### Editar un paquete existente
- `cd types/my-package-to-edit`
- Haz cambios. Recuerda editar las pruebas.
Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal).
- También puede que quieras añadirle la sección "Definitions by" en el encabezado del paquete.
- Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete.
- Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- O si hay más personas, puede ser multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
- Si hay un `tslint.json`, ejecuta `npm run lint package-name`. De lo contrario, ejecuta `tsc` en el directorio del paquete.
* `cd types/my-package-to-edit`
* Haz cambios. Recuerda editar las pruebas.
Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal).
* También puede que quieras añadirle la sección "Definitions by" en el encabezado del paquete.
- Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete.
- Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- O si hay más personas, puede ser multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Si hay un `tslint.json`, ejecuta `npm run lint package-name`. De lo contrario, ejecuta `tsc` en el directorio del paquete.
Cuando hagas un PR para editar un paquete existente, `dt-bot` deberá @-mencionar a los autores previos.
Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
#### Crear un nuevo paquete
Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en Definitely Typed.
@@ -137,12 +144,12 @@ Si el paquete al que le estás agregando typings no es para NPM, asegúrate de q
Tu paquete debería tener esta estructura:
| Archivo | Propósito |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| index.d.ts | Este contiene los typings del paquete. |
| foo-tests.ts | 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 | Este permite ejecutar `tsc` dentro del paquete. |
| tslint.json | Permite linting. |
| Archivo | Propósito |
| --- | --- |
| index.d.ts | Este contiene los typings del paquete. |
| foo-tests.ts | 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 | Este permite ejecutar `tsc` dentro del paquete. |
| tslint.json | Permite linting. |
Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name my-package-name --template module`.
Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen).
@@ -153,41 +160,43 @@ Los miembros de Definitely Typed frecuentemente monitorean nuevos PRs, pero ten
Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
#### Errores comunes
- Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
- Formatear: Utiliza 4 espacios.
- `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una función no escribe a sus parámetros.
- `interface Foo { new(): Foo; }`:
* Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatear: Utiliza 4 espacios.
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una función no escribe a sus parámetros.
* `interface Foo { new(): Foo; }`:
Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`.
- `const Class: { new(): IClass; }`:
* `const Class: { new(): IClass; }`:
Prefiere usar una declaración de clase `class Class { constructor(); }` En vez de una nueva constante.
- `getMeAT<T>(): T`:
* `getMeAT<T>(): T`:
Si un tipo de parámetro no aparece en los tipos de ningún parámetro, no tienes una función genérica, solo tienes un afirmación del tipo disfrazado.
Prefiera utilizar una afirmación de tipo real, p.ej. `getMeAT() as number`.
Prefiera utilizar una afirmación de tipo real, p.ej. `getMeAT() as number`.
Un ejemplo donde un tipo de parámetro es aceptable: `function id<T>(value: T): T;`.
Un ejemplo donde no es aceptable: `function parseJson<T>(json: string): T;`.
Una excepción: `new Map<string, number>()` está bien.
- Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más específico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
- `var foo: string | any`:
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más específico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
* `var foo: string | any`:
Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`.
Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`.
#### Remover un paquete
Cuando un paquete [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) sus propios tipos, estos tipos deberán ser removidos de Definitely Typed para evitar que generen confusión.
Se puede remover ejecutando `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [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.
- `sourceRepoURL`: Esto debería señalar el repositorio que contiene los typings.
- `libraryName`: Un nombre descriptivo de la librería, p.ej. "Angular 2" en vez de "angular2". (Si es omitido, será idéntico a "typingsPackageName".)
- `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.
- `sourceRepoURL`: Esto debería señalar el repositorio que contiene los typings.
- `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` con `"dependencies": { "foo": "x.y.z" }`.
Si un paquete nunca estuvo en Definitely Typed, no será necesario añadirlo a `notNeededPackages.json`.
#### Lint
Para realizar el lint a un paquete, solo añade `tslint.json` al paquete que contiene `{ "extends": "dtslint/dt.json" }`. Todos los paquetes nuevos deberán pasar por el proceso de linted.
@@ -212,7 +221,7 @@ Para afirmar que una expresión es de un tipo dado, utilice `$ExpectType`. Para
f(1);
// $ExpectError
f('one');
f("one");
```
Para más detalles, vea el [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
@@ -220,11 +229,12 @@ Para más detalles, vea el [dtslint](https://github.com/Microsoft/dtslint#write-
Realiza una prueba ejecutando `npm run lint package-name` donde `package-name` es el nombre de tu paquete.
Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
## FAQ
#### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM?
La `master` branch es automáticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
La `master` branch es automáticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
#### He enviado un pull request. ¿Cuánto tardará en ser merged?
@@ -256,7 +266,7 @@ Aquí están las [definiciones solicitadas actualmente](https://github.com/Defin
#### ¿Qué pasa con las type definitions para el DOM?
Si las types son parte de los estándares web, estas deberán ser contribuidas a [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) para que se hagan parte de la librería predeterminada `lib.dom.d.ts`.
Si las types son parte de los estándares web, estas deberán ser contribuidas a [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) para que se hagan parte de la librería predeterminada `lib.dom.d.ts`.
#### Un paquete utiliza `export =`, pero prefiero utilizar las import predeterminadas. ¿Puedo cambiar `export =` por `export default`?
@@ -290,10 +300,13 @@ Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": ["history/v2"]
}
"history": [ "history/v2" ]
},
},
"files": ["index.d.ts", "history-tests.ts"]
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
@@ -306,9 +319,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.
@@ -321,8 +334,8 @@ Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedade
```json
{
"paths": {
"@foo/*": ["foo__*"]
"paths":{
"@foo/*": ["foo__*"]
}
}
```

View File

@@ -2,33 +2,33 @@
> 이 저장소는 고품질의 타입스크립트(TypeScript) 자료형 정의(Type definition)를 위한 저장소입니다.
_이 도움말은 [영어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [스페인어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [러시아어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md), 그리고 [중국어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.cn.md)로도 읽으실 수 있습니다!_
*이 도움말은 [영어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [스페인어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [러시아어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md), 그리고 [중국어](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.cn.md)로도 읽으실 수 있습니다!*
_[관리자 설명서](./docs/admin.md) 링크_
*[관리자 설명서](./docs/admin.md) 링크*
## 목차
- [현재 상태](#현재-상태)
- [어떻게 기여하나요?](#어떻게-기여하나요)
- [테스트](#테스트)
- [풀 리퀘스트 만들기](#풀-리퀘스트pull-request-만들기)
- [이미 존재하는 패키지를 수정하기](#이미-존재하는-패키지를-수정하기)
- [새 패키지를 만들기](#새-패키지를-만들기)
- [많이 저지르는 실수들](#많이-저지르는-실수들)
- [패키지 삭제하기](#패키지-삭제하기)
- [린터](#린터)
- [검증하기](#검증하기)
- [자주 하는 질문들](#자주-하는-질문들)
* [현재 상태](#현재-상태)
* [어떻게 기여하나요?](#어떻게-기여하나요)
* [테스트](#테스트)
* [풀 리퀘스트 만들기](#풀-리퀘스트pull-request-만들기)
* [이미 존재하는 패키지를 수정하기](#이미-존재하는-패키지를-수정하기)
* [새 패키지를 만들기](#새-패키지를-만들기)
* [많이 저지르는 실수들](#많이-저지르는-실수들)
* [패키지 삭제하기](#패키지-삭제하기)
* [린터](#린터)
* [검증하기](#검증하기)
* [자주 하는 질문들](#자주-하는-질문들)
## 현재 상태
저장소 및 퍼블리싱 과정의 상태를 표시합니다.
기여자분들이 작성한 PR 또는 패키지에 문제가 발생했을 경우 이 표시를 보면 도움이 될 수 있습니다.
- 최신 빌드가 [타입 체크/린트](https://github.com/Microsoft/dtslint) 과정을 깔끔하게 통과했습니다: [![Build Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.DefinitelyTyped?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=1&branchName=master)
- 모든 패키지가 typescript@next상에서 타입 체크/린트 과정을 깔끔하게 통과합니다: [![Build status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/Nightly%20dtslint)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=8)
- 모든 패키지가 1시간 내에 [npm에 배포](https://github.com/microsoft/types-publisher)되었습니다: [![Publish Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.types-publisher-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=5&branchName=master)
- [typescript-bot](https://github.com/typescript-bot)이 Definitely Typed에서 잘 돌고 있습니다 [![Activity Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.typescript-bot-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=6&branchName=master)
* 최신 빌드가 [타입 체크/린트](https://github.com/Microsoft/dtslint) 과정을 깔끔하게 통과했습니다: [![Build Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.DefinitelyTyped?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=1&branchName=master)
* 모든 패키지가 typescript@next상에서 타입 체크/린트 과정을 깔끔하게 통과합니다: [![Build status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/Nightly%20dtslint)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=8)
* 모든 패키지가 1시간 내에 [npm에 배포](https://github.com/microsoft/types-publisher)되었습니다: [![Publish Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.types-publisher-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=5&branchName=master)
* [typescript-bot](https://github.com/typescript-bot)이 Definitely Typed에서 잘 돌고 있습니다 [![Activity Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.typescript-bot-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=6&branchName=master)
상태 표시가 비정상이거나 고장 표시가 발생하면 [Definitely Typed Discord 채널](https://discord.gg/typescript)에서 이 문제를 알려주세요.
@@ -71,43 +71,44 @@ TypeScript 2.0에서 3.1 버전을 사용하는 경우, 그래도 `@types` 패
그러나 작동 여부를 보장하지는 못합니다.
지원 기간은 다음과 같습니다:
| 버전 | 출시일 | 지원 종료 |
| ---- | ----------- | ----------- |
| 2.8 | 2018년 3월 | 2020년 3월 |
| 2.9 | 2018년 5월 | 2020년 5월 |
| 3.0 | 2018년 7월 | 2020년 7월 |
| 3.1 | 2018년 9월 | 2020년 9월 |
| 3.2 | 2018년 11월 | 2020년 11월 |
| 3.3 | 2019년 1월 | 2021년 1월 |
| 3.4 | 2019년 3월 | 2021년 3월 |
| 3.5 | 2019년 5월 | 2021년 5월 |
| 3.6 | 2019년 8월 | 2021년 8월 |
| 3.7 | 2019년 11월 | 2021년 11월 |
| 3.8 | 2020년 2월 | 2022년 2월 |
| 3.9 | 2020년 5월 | 2022년 5월 |
| 4.0 | 2020년 8월 | 2022년 8월 |
버전 | 출시일 | 지원 종료
-- | -- | --
2.8 | 2018년 3월 | 2020년 3월
2.9 | 2018년 5월 | 2020년 5월
3.0 | 2018년 7월 | 2020년 7월
3.1 | 2018년 9월 | 2020년 9월
3.2 | 2018년 11월 | 2020년 11월
3.3 | 2019년 1월 | 2021년 1월
3.4 | 2019년 3월 | 2021년 3월
3.5 | 2019년 5월 | 2021년 5월
3.6 | 2019년 8월 | 2021년 8월
3.7 | 2019년 11월 | 2021년 11월
3.8 | 2020년 2월 | 2022년 2월
3.9 | 2020년 5월 | 2022년 5월
4.0 | 2020년 8월 | 2022년 8월
`@types` 패키지 안에는 패키지가 확실하게 지원하는 TypeScript 버전이 태그로 쓰여 있으므로, 2년 지원 기간이 지난 오래된 패키지도 보통 찾아보실 수 있습니다.
예를 들어, `npm dist-tags @types/react` 명령어를 입력하면 TypeScript 2.5는 react@16.0용 타입을, TypeScript 2.6 및 2.7은 react@16.4용 타입을 사용할 수 있는 것을 확인하실 수 있습니다:
| 태그 | 버전 |
| ------ | ------- |
| latest | 16.9.23 |
| ts2.0 | 15.0.1 |
| ... | ... |
| ts2.5 | 16.0.36 |
| ts2.6 | 16.4.7 |
| ts2.7 | 16.4.7 |
| ... | ... |
|태그 | 버전|
|----|---------|
|latest| 16.9.23|
|ts2.0| 15.0.1|
| ... | ... |
|ts2.5| 16.0.36|
|ts2.6| 16.4.7|
|ts2.7| 16.4.7|
| ... | ... |
#### TypeScript 1.\*
#### TypeScript 1.*
- 이 저장소의 `master` 브랜치에서 직접 다운로드해 프로젝트에 삽입하기
- ~~[Typings](https://github.com/typings/typings)를 사용하기~~ (다른 방법을 사용해주세요. typings는 더이상 추천하지 않습니다)
- ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped) 을 사용하기~~ (다른 방법을 사용해주세요. NuGet은 더 이상 DT 자료형(Typing)을 제공하지 않습니다.)
* 이 저장소의 `master` 브랜치에서 직접 다운로드해 프로젝트에 삽입하기
* ~~[Typings](https://github.com/typings/typings)를 사용하기~~ (다른 방법을 사용해주세요. typings는 더이상 추천하지 않습니다)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped) 을 사용하기~~ (다른 방법을 사용해주세요. NuGet은 더 이상 DT 자료형(Typing)을 제공하지 않습니다.)
위 방법을 사용할 경우 수동으로 [참조(Reference)](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)를 추가해주어야 할 수 있습니다.
## 어떻게 기여하나요?
Definitely Typed는 여러분과 같은 많은 기여자들의 도움 덕분에 돌아가고 있습니다!
@@ -121,6 +122,7 @@ Definitely Typed는 여러분과 같은 많은 기여자들의 도움 덕분에
새로운 기능을 추가하려면 [모듈 증강(module augmentation)](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)를 사용할 수 있습니다.
물론 `node_modules/@types/foo/index.d.ts` 를 직접 수정하실 수도 있으며, 이 파일을 복사한 다음 아래의 과정을 따라하실 수도 있습니다.
#### 새 패키지를 테스트하기
사용하고 계신 `tsconfig.json` 에 다음 내용을 추가해주세요.
@@ -137,32 +139,35 @@ Definitely Typed는 여러분과 같은 많은 기여자들의 도움 덕분에
실제 코드를 통한 확인이 끝나면, [풀 리퀘스트(Pull request)](#풀-리퀘스트pull-request-만들기)를 만들어주세요.
[이미 존재하는 패키지를 수정](#이미-존재하는-패키지를-수정하기)하거나 [새 패키지를 만들기](#새-패키지-만들기)위한 과정들을 따라하시면 됩니다.
### 풀 리퀘스트(Pull request) 만들기
패키지가 잘 작동하는지 확인하셨다면, Definitely Typed에 공유해주세요.
우선, 이 저장소를 [포크(fork)](https://guides.github.com/activities/forking/)해 주시고, [node](https://nodejs.org/) 를 설치하신 뒤, `npm install` 명령을 실행해주세요.
#### 이미 존재하는 패키지를 수정하기
- `cd types/my-package-to-edit` 명령을 실행합니다.
- 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요!
만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#패키지를-새-메이저-버전major-version에-맞게-갱신하고-싶어요)을 꼭 올려주세요.
- 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다.
- 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다.
- `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>` 와 같이 여러분의 이름을 줄의 맨 마지막에 추가할 수 있습니다.
- 사람이 너무 많을 경우엔, 다음과 같이 여러 줄로 쓰실 수도 있습니다.
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
- `tslint.json` 파일이 있는 경우에는, `npm run lint package-name` 명령을 실행시키고 결과를 확인해주세요. 그렇지 않은 경우에는, 해당 패키지가 있는 디렉토리 안에서 `tsc` 명령을 실행시키고 결과를 확인해주세요.
* `cd types/my-package-to-edit` 명령을 실행합니다.
* 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요!
만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#패키지를-새-메이저-버전major-version에-맞게-갱신하고-싶어요)을 꼭 올려주세요.
* 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다.
- 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다.
- `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>` 와 같이 여러분의 이름을 줄의 맨 마지막에 추가할 수 있습니다.
- 사람이 너무 많을 경우엔, 다음과 같이 여러 줄로 쓰실 수도 있습니다.
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `tslint.json` 파일이 있는 경우에는, `npm run lint package-name` 명령을 실행시키고 결과를 확인해주세요. 그렇지 않은 경우에는, 해당 패키지가 있는 디렉토리 안에서 `tsc` 명령을 실행시키고 결과를 확인해주세요.
이미 존재하는 패키지에 대한 풀 리퀘스트(Pull request)를 만들었을 경우에는, `dt-bot` 이 이전 저자들을 자동으로 호출하는지 확인해주세요.
그렇지 않은 경우에는, 여러분이 직접 풀 리퀘스트(Pull request)와 관계있는 사람들을 호출할 수도 있습니다.
#### 새 패키지를 만들기
만약 라이브러리를 만드는 중이고 라이브러리가 타입스크립트(TypeScript)로 쓰여있다면, Definitely Typed 에 선언(Declaration)을 올리는 대신 패키지에 [자동생성된 선언(Declaration) 파일을 포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)시킬 수 있습니다.
@@ -173,12 +178,12 @@ NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지
새 자료형 패키지는 다음과 같은 구조로 구성되어있어야만 합니다.
| 파일 이름 | 용도 |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
| 파일 이름 | 용도 |
| --- | --- |
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name my-package-name --template module` 명령으로,
그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name my-package-name --template module` 명령으로 만들 수 있습니다.
@@ -191,41 +196,43 @@ Definitely Typed 의 관리자들이 주기적으로 새로운 풀 리퀘스트(
[base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js) 패키지는 좋은 예시 중 하나입니다.
#### 많이 저지르는 실수들
- 우선, [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)에 나와있는 내용들을 따라주세요.
- 코드에서는 모든 곳에서 탭(Tab)을 사용하거나, 항상 4 개의 띄어쓰기를 사용해주세요.
- `function sum(nums: number[]): number`의 경우, 만약 함수가 인자를 변경하지 않는다면 `ReadonlyArray` 를 사용해주세요.
- `interface Foo { new(): Foo; }`의 경우,
* 우선, [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)에 나와있는 내용들을 따라주세요.
* 코드에서는 모든 곳에서 탭(Tab)을 사용하거나, 항상 4 개의 띄어쓰기를 사용해주세요.
* `function sum(nums: number[]): number`의 경우, 만약 함수가 인자를 변경하지 않는다면 `ReadonlyArray` 를 사용해주세요.
* `interface Foo { new(): Foo; }`의 경우,
이런 선언은 이 형(Type)을 가진 객체(Object)에 `new` 를 사용할 수 있도록 만듭니다. 많은 경우 여러분은 `declare class Foo { constructor(); }` 를 사용하려는 것일 겁니다.
- `const Class: { new(): IClass; }`의 경우,
* `const Class: { new(): IClass; }`의 경우,
`new` 를 사용할 수 있는 상수를 만드는 대신, `class Class { constructor(); }` 와 같이 클래스 선언(Class declaration)을 사용하는 게 더 좋습니다.
- `getMeAT<T>(): T`의 경우,
* `getMeAT<T>(): T`의 경우,
만일 자료형 매개변수(Type parameter)가 함수의 매개변수에 등장하지 않는다면, 그런 제너릭(Generic) 함수를 사용할 필요가 없습니다.
그 제너릭(Generic) 함수는 단순히 자료형 단언(Type assertion)을 위장시킨 것뿐입니다. 이 경우 `getMeAT() as number` 와 같이 진짜 자료형 단언(Type assertion) 을 사용하는 게 더 좋습니다.
다음은 괜찮은 제너릭(Generic)의 예시입니다. `function id<T>(value: T): T;`.
다음은 문제가 있는 제너릭(Generic)의 예시입니다. `function parseJson<T>(json: string): T;`.
예외적으로, `new Map<string, number>()` 와 같은 경우는 괜찮습니다.
- `Function` 이나 `Object` 와 같은 형(Type)을 사용하는 것은 대부분의 경우 문제를 일으킵니다. 99% 의 경우 더 구체적인 형(Type)을 사용하는게 가능합니다. [함수(Function)](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) 를 위해서는 `(x: number) => number` 와 같은, 객체를 위해서는 `{ x: number, y: number }` 와 같은 형(Type)들을 사용할 수 있습니다. 형(Type)에 대한 정보가 전혀 없을 경우에는, `Object` 형(Type)이 아니라 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 형(Type)을 사용해야 합니다. 만일 어떤 형(Type)이 객체라는 사실만 알고 있는 경우, `Object` 나 `{ [key: string]: any }` 가 아니라 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type) 를 사용해주세요.
- `var foo: string | any`의 경우,
* `Function` 이나 `Object` 와 같은 형(Type)을 사용하는 것은 대부분의 경우 문제를 일으킵니다. 99% 의 경우 더 구체적인 형(Type)을 사용하는게 가능합니다. [함수(Function)](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) 를 위해서는 `(x: number) => number` 와 같은, 객체를 위해서는 `{ x: number, y: number }` 와 같은 형(Type)들을 사용할 수 있습니다. 형(Type)에 대한 정보가 전혀 없을 경우에는, `Object` 형(Type)이 아니라 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 형(Type)을 사용해야 합니다. 만일 어떤 형(Type)이 객체라는 사실만 알고 있는 경우, `Object` 나 `{ [key: string]: any }` 가 아니라 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type) 를 사용해주세요.
* `var foo: string | any`의 경우,
`any` 가 합 자료형(Union type)의 안에서 사용될 경우, 결과 형(Type)은 언제나 `any` 가 됩니다. 따라서 형(Type)의 `string` 부분이 유용해 보인다 하더라도, 사실은 자료형 검사(Type checking)의 측면에서 `any` 와 다른 것이 없습니다.
대신, `any`, `string`, 나 `string | object` 중 하나를 필요에 맞게 골라서 사용해주세요.
#### 패키지 삭제하기
패키지가 스스로의 형(Type)을 [포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하게 되면, Definitely Typed 에 있는 자료형(Typing) 패키지를 삭제하는 것이 좋습니다.
`npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]` 명령어를 사용하여 자료형(Typing) 패키지를 삭제할 수 있습니다.
- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다.
- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다.
- `sourceRepoURL` 는 자료형(Typing)을 포함하게 된 저장소의 주소입니다.
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.)
- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다.
- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다.
- `sourceRepoURL` 는 자료형(Typing)을 포함하게 된 저장소의 주소입니다.
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.)
Definitely Typed 의 다른 패키지들이 삭제된 자료형(Typing) 패키지를 사용하고 있을 경우, 형(Type)을 포함하기 시작한 원래 패키지를 사용하도록 수정해야합니다. 삭제된 자료형(Typing) 패키지를 사용하는 각 Definitely Typed 패키지들의 `package.json` 파일에 `"dependencies": { "foo": "x.y.z" }` 를 추가해주시면 됩니다.
Definitely Typed 에 한 번도 올라온 적 없는 패키지가 형(Type)을 포함하게 되었다면, `notNeededPackages.json` 파일에 추가할 필요도 없습니다.
#### 린터
자료형(Typing) 패키지를 린트(Lint)하려면, 패키지 디렉토리에 `{ "extends": "dtslint/dt.json" }` 를 포함하고 있는 `tslint.json` 파일을 추가해주시면 됩니다. 모든 새 패키지는 해당 파일을 가지고 있어야 합니다.
@@ -250,7 +257,7 @@ Definitely Typed 에 한 번도 올라온 적 없는 패키지가 형(Type)을
f(1);
// $ExpectError
f('one');
f("one");
```
[dtslint](https://github.com/Microsoft/dtslint#write-tests) 저장소의 README 파일에서 더 자세한 내용을 확인하실 수 있습니다.
@@ -261,6 +268,7 @@ f('one');
작성한 dts 파일을 타입스크립트 컴파일러로 돌려보기 위해 테스트 스크립트 내부적으로 [dtslint](https://github.com/Microsoft/dtslint)를 사용합니다.
## 자주 하는 질문들
#### 이 저장소와 `@types` 패키지들이 대체 무슨 관계가 있는 건가요?
@@ -332,10 +340,13 @@ NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": ["history/v2"]
}
"history": [ "history/v2" ]
},
},
"files": ["index.d.ts", "history-tests.ts"]
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
@@ -363,12 +374,13 @@ NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `
```json
{
"paths": {
"@foo/*": ["foo__*"]
"paths":{
"@foo/*": ["foo__*"]
}
}
```
#### 깃헙(GitHub)이 보여주는 파일 히스토리(History)가 불완전해요.
깃헙은 이름이 바뀐 파일의 히스토리(History)를 [지원하지 않습니다](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames). 대신 [`git log --follow`](https://www.git-scm.com/docs/git-log) 명령을 사용하세요.

260
README.md
View File

@@ -1,35 +1,35 @@
# Definitely Typed
> The repository for _high quality_ TypeScript type definitions.
> The repository for *high quality* TypeScript type definitions.
_You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md), [Chinese](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.cn.md) and [Portuguese](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.pt.md)!_
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md), [Chinese](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.cn.md) and [Portuguese](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.pt.md)!*
_Link to [Admin manual](./docs/admin.md)_
*Link to [Admin manual](./docs/admin.md)*
## Table of Contents
- [Current status](#current-status)
- [How can I contribute?](#how-can-i-contribute)
- [Testing](#testing)
- [Make a pull request](#make-a-pull-request)
- [Edit an existing package](#edit-an-existing-package)
- [Create a new package](#create-a-new-package)
- [Common mistakes](#common-mistakes)
- [Removing a package](#removing-a-package)
- [Linter](#linter)
- [Verifying](#verifying)
- [FAQ](#faq)
* [Current status](#current-status)
* [How can I contribute?](#how-can-i-contribute)
- [Testing](#testing)
- [Make a pull request](#make-a-pull-request)
- [Edit an existing package](#edit-an-existing-package)
- [Create a new package](#create-a-new-package)
- [Common mistakes](#common-mistakes)
- [Removing a package](#removing-a-package)
- [Linter](#linter)
- [Verifying](#verifying)
* [FAQ](#faq)
## Current status
This section tracks the health of the repository and publishing process.
It may be helpful for contributors experiencing any issues with their PRs and packages.
- Most recent build [type-checked/linted](https://github.com/Microsoft/dtslint) cleanly: [![Build Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.DefinitelyTyped?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=1&branchName=master)
- All packages are type-checking/linting cleanly on typescript@next: [![Build status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/Nightly%20dtslint)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=8)
- All packages are being [published to npm](https://github.com/microsoft/types-publisher) in under an hour: [![Publish Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.types-publisher-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=5&branchName=master)
- [typescript-bot](https://github.com/typescript-bot) has been active on Definitely Typed [![Activity Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.typescript-bot-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=6&branchName=master)
- Current [infrastructure status updates](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/44317)
* Most recent build [type-checked/linted](https://github.com/Microsoft/dtslint) cleanly: [![Build Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.DefinitelyTyped?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=1&branchName=master)
* All packages are type-checking/linting cleanly on typescript@next: [![Build status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/Nightly%20dtslint)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=8)
* All packages are being [published to npm](https://github.com/microsoft/types-publisher) in under an hour: [![Publish Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.types-publisher-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=5&branchName=master)
* [typescript-bot](https://github.com/typescript-bot) has been active on Definitely Typed [![Activity Status](https://dev.azure.com/definitelytyped/DefinitelyTyped/_apis/build/status/DefinitelyTyped.typescript-bot-watchdog?branchName=master)](https://dev.azure.com/definitelytyped/DefinitelyTyped/_build/latest?definitionId=6&branchName=master)
* Current [infrastructure status updates](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/44317)
If anything here seems wrong, or any of the above are failing, please let us know in [the Definitely Typed channel on the TypeScript Community Discord server](https://discord.gg/typescript).
@@ -100,11 +100,11 @@ For example, if you run `npm dist-tags @types/react`, you'll see that TypeScript
| ts2.7 | 16.4.7 |
| ... | ... |
#### TypeScript 1.\*
#### TypeScript 1.*
- Manually download from the `master` branch of this repository and place them in your project
- ~~[Typings](https://github.com/typings/typings)~~ (use preferred alternatives, typings is deprecated)
- ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* Manually download from the `master` branch of this repository and place them in your project
* ~~[Typings](https://github.com/typings/typings)~~ (use preferred alternatives, typings is deprecated)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
@@ -132,7 +132,7 @@ Add to your `tsconfig.json`:
Create `types/foo/index.d.ts` containing declarations for the module "foo".
You should now be able to import from `"foo"` in your code and it will route to the new type definition.
Then build _and_ run the code to make sure your type definition actually corresponds to what happens at runtime.
Then build *and* run the code to make sure your type definition actually corresponds to what happens at runtime.
If you're wondering where to start with test code, the examples in the README of the module are a great place to start.
@@ -152,11 +152,11 @@ We use a bot to let a large number of pull requests to DefinitelyTyped be handle
#### Edit an existing package
- `cd types/my-package-to-edit`
- Make changes. Remember to edit tests.
If you make breaking changes, do not forget to [update a major version](#if-a-library-is-updated-to-a-new-major-version-with-breaking-changes-how-should-i-update-its-type-declaration-package).
* `cd types/my-package-to-edit`
* Make changes. Remember to edit tests.
If you make breaking changes, do not forget to [update a major version](#if-a-library-is-updated-to-a-new-major-version-with-breaking-changes-how-should-i-update-its-type-declaration-package).
- If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.
* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
If it doesn't, you can do so yourself in the comment associated with the PR.
@@ -206,12 +206,12 @@ If the package you are adding typings for is not on NPM, make sure the name you
Your package should have this structure:
| File | Purpose |
| ------------- | ---------------------------------------------------------------------------------------------------- |
| index.d.ts | This contains the typings for the package. |
| foo-tests.ts | This contains sample code which tests the typings. This code does _not_ run, but it is type-checked. |
| tsconfig.json | This allows you to run `tsc` within the package. |
| tslint.json | Enables linting. |
| File | Purpose |
| ------------- | ------- |
| index.d.ts | This contains the typings for the package. |
| foo-tests.ts | This contains sample code which tests the typings. This code does *not* run, but it is type-checked. |
| tsconfig.json | This allows you to run `tsc` within the package. |
| tslint.json | Enables linting. |
Generate these by running `npx dts-gen --dt --name my-package-name --template module` if you have npm ≥ 5.2.0, `npm install -g dts-gen` and `dts-gen --dt --name my-package-name --template module` otherwise.
See all options at [dts-gen](https://github.com/Microsoft/dts-gen).
@@ -228,58 +228,56 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
DT has the concept of "Definition Owners" which are people who want to maintain the quality of a particular module's types
- Adding yourself to the list will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package.
- Your PR reviews will have a higher precedence of importance to [the bot](https://github.com/DefinitelyTyped/dt-mergebot) which maintains this repo.
- The DT maintainers are putting trust in the definition owners to ensure a stable eco-system, please don't add yourself lightly.
* Adding yourself to the list will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package.
* Your PR reviews will have a higher precedence of importance to [the bot](https://github.com/DefinitelyTyped/dt-mergebot) which maintains this repo.
* The DT maintainers are putting trust in the definition owners to ensure a stable eco-system, please don't add yourself lightly.
To Add yourself as a Definition Owner:
- Adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
- Or if there are more people, it can be multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
* Or if there are more people, it can be multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
Once a week the Definition Owners are synced to the file [.github/CODEOWNERS](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/.github/CODEOWNERS) which is our source of truth.
#### Common mistakes
- First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
- Formatting: Use 4 spaces. Prettier is set up on this repo, so you can run `npm run prettier -- --write path/to/package/**/*.ts`. [When using assertions](https://github.com/SamVerschueren/tsd#assertions), add `// prettier-ignore` exclusion to mark line(s) of code as excluded from formatting:
```tsx
// prettier-ignore
const incompleteThemeColorModes: Theme = { colors: { modes: { papaya: { // $ExpectError
```
- `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters.
- `interface Foo { new(): Foo; }`:
This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`.
- `const Class: { new(): IClass; }`:
Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant.
- `getMeAT<T>(): T`:
If a type parameter does not appear in the types of any parameters, you don't really have a generic function, you just have a disguised type assertion.
Prefer to use a real type assertion, e.g. `getMeAT() as number`.
Example where a type parameter is acceptable: `function id<T>(value: T): T;`.
Example where it is not acceptable: `function parseJson<T>(json: string): T;`.
Exception: `new Map<string, number>()` is OK.
- Using the types `Function` and `Object` is almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are `(x: number) => number` for [functions](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` for objects. If there is no certainty at all about the type, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) is the right choice, not `Object`. If the only known fact about the type is that it's some object, use the type [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), not `Object` or `{ [key: string]: any }`.
- `var foo: string | any`:
When `any` is used in a union type, the resulting type is still `any`. So while the `string` portion of this type annotation may _look_ useful, it in fact offers no additional typechecking over simply using `any`.
Depending on the intention, acceptable alternatives could be `any`, `string`, or `string | object`.
* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatting: Use 4 spaces. Prettier is set up on this repo, so you can run `npm run prettier --write path/to/package/**/*.ts`. [When using assertions](https://github.com/SamVerschueren/tsd#assertions), add `// prettier-ignore` exclusion to mark line(s) of code as excluded from formatting:
```tsx
// prettier-ignore
const incompleteThemeColorModes: Theme = { colors: { modes: { papaya: { // $ExpectError
```
* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters.
* `interface Foo { new(): Foo; }`:
This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Prefer to use a class declaration `class Class { constructor(); }` instead of a new-able constant.
* `getMeAT<T>(): T`:
If a type parameter does not appear in the types of any parameters, you don't really have a generic function, you just have a disguised type assertion.
Prefer to use a real type assertion, e.g. `getMeAT() as number`.
Example where a type parameter is acceptable: `function id<T>(value: T): T;`.
Example where it is not acceptable: `function parseJson<T>(json: string): T;`.
Exception: `new Map<string, number>()` is OK.
* Using the types `Function` and `Object` is almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are `(x: number) => number` for [functions](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` for objects. If there is no certainty at all about the type, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) is the right choice, not `Object`. If the only known fact about the type is that it's some object, use the type [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), not `Object` or `{ [key: string]: any }`.
* `var foo: string | any`:
When `any` is used in a union type, the resulting type is still `any`. So while the `string` portion of this type annotation may _look_ useful, it in fact offers no additional typechecking over simply using `any`.
Depending on the intention, acceptable alternatives could be `any`, `string`, or `string | object`.
#### Removing a package
When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from Definitely Typed to avoid confusion.
You can remove it by running `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [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.
- `sourceRepoURL`: This should point to the repository that contains the typings.
- `libraryName`: Name of npm package that replaces the Definitely Typed types. Usually this is identical to "typingsPackageName", in which case you can omit it.
You can remove it by running `npm run not-needed typingsPackageName asOfVersion sourceRepoURL [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.
* `sourceRepoURL`: This should point to the repository that contains the typings.
* `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`.
@@ -288,10 +286,10 @@ For example:
```json
{
"private": true,
"dependencies": {
"foo": "^2.6.0"
}
"private": true,
"dependencies": {
"foo": "^2.6.0"
}
}
```
@@ -305,7 +303,7 @@ All new packages must be linted. To lint a package, add a `tslint.json` to that
```js
{
"extends": "dtslint/dt.json"
"extends": "dtslint/dt.json"
}
```
@@ -313,11 +311,11 @@ This should be the only content in a finished project's `tslint.json` file. If a
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
@@ -330,7 +328,7 @@ To assert that an expression is of a given type, use `$ExpectType`. To assert th
f(1);
// $ExpectError
f('one');
f("one");
```
For more details, see [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
@@ -404,9 +402,8 @@ This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/quest
It is more appropriate to import the module using the `import foo = require("foo");` syntax.
Nevertheless, if you want to use a default import like `import foo from "foo";` you have two options:
- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm).
- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since TypeScript 2.7).
- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm).
- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since TypeScript 2.7).
#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?
@@ -421,43 +418,42 @@ For an NPM package, `export =` is accurate if `node -p 'require("foo")'` works t
Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// Minimum TypeScript Version: 3.3`.
However, if your project needs to maintain types that are compatible with, say, 3.7 and above _at the same time as_ types that are compatible with 3.6 or below, you will need to use the `typesVersions` feature.
However, if your project needs to maintain types that are compatible with, say, 3.7 and above *at the same time as* types that are compatible with 3.6 or below, you will need to use the `typesVersions` feature.
You can find a detailed explanation of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions).
Here's a short example to get you started:
1. You'll have to add a `package.json` file to your package definition, with the following contents:
```json
{
"private": true,
"types": "index",
"typesVersions": {
"<=3.6": { "*": ["ts3.6/*"] }
}
}
```
```json
{
"private": true,
"types": "index",
"typesVersions": {
"<=3.6": { "*": ["ts3.6/*"] }
}
}
```
2. Create the sub-directory mentioned in the `typesVersions` field inside your types directory (`ts3.6/` in this example).
`ts3.6/` will support TypeScript versions 3.6 and below, so copy the existing types and tests there.
You'll need to delete the definition header from `ts3.6/index.d.ts` since only the root `index.d.ts` is supposed to have it.
You'll need to delete the definition header from `ts3.6/index.d.ts` since only the root `index.d.ts` is supposed to have it.
3. Set the `baseUrl` and `typeRoots` options in `ts3.6/tsconfig.json` to the correct paths, which should look something like this:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"]
}
}
```
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"]
}
}
```
4. Back in the root of the package, add the TypeScript 3.7 features you want to use.
When people install the package, TypeScript 3.6 and below will start from `ts3.6/index.d.ts`, whereas TypeScript 3.7 and above will start from `index.d.ts`.
You can look at [styled-components](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/styled-components).
You can look at [styled-components](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/styled-components) for an example.
#### I want to add a DOM API not present in TypeScript by default.
@@ -468,7 +464,7 @@ When it graduates draft mode, we may remove it from Definitely Typed and depreca
#### How do Definitely Typed package versions relate to versions of the corresponding library?
_NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_
*NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)*
Each Definitely Typed package is versioned when published to NPM.
The [types-publisher](https://github.com/Microsoft/types-publisher) (the tool that publishes `@types` packages to npm) will set the declaration package's version by using the `major.minor` version number listed in the first line of its `index.d.ts` file.
@@ -491,13 +487,13 @@ Sometimes type declaration package versions and library package versions can get
Below are a few common reasons why, in order of how much they inconvenience users of a library.
Only the last case is typically problematic.
- As noted above, the patch version of the type declaration package is unrelated to the library patch version.
This allows Definitely Typed to safely update type declarations for the same major/minor version of a library.
- If updating a package for new functionality, don't forget to update the version number to line up with that version of the library.
If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work.
- It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update Definitely Typed when new library features are released.
So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release.
If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member!
* As noted above, the patch version of the type declaration package is unrelated to the library patch version.
This allows Definitely Typed to safely update type declarations for the same major/minor version of a library.
* If updating a package for new functionality, don't forget to update the version number to line up with that version of the library.
If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work.
* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update Definitely Typed when new library features are released.
So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release.
If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member!
:exclamation: If you're updating type declarations for a library, always set the `major.minor` version in the first line of `index.d.ts` to match the library version that you're documenting! :exclamation:
@@ -523,14 +519,17 @@ At the time of writing, the [history v2 `tsconfig.json`](https://github.com/Defi
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": ["history/v2"]
}
},
"files": ["index.d.ts", "history-tests.ts"]
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
}
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
@@ -544,9 +543,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.
@@ -554,14 +553,13 @@ Please note that it is not required to fully exercise the definition in each tes
Types for a scoped package `@foo/bar` should go in `types/foo__bar`. Note the double underscore.
When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated
`tsconfig.json` to correctly reference the scoped package:
When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated `tsconfig.json` to correctly reference the scoped package:
```json
{
"paths": {
"@foo/*": ["foo__*"]
}
"paths": {
"@foo/*": ["foo__*"]
}
}
```

File diff suppressed because it is too large Load Diff

View File

@@ -77,21 +77,22 @@ npm install --save-dev @types/node
График обновлений:
| Версия | Релиз | Окончание поддержки |
| ------ | ------------- | ------------------- |
| 2.8 | Март 2018 | Март 2020 |
| 2.9 | Май 2018 | Май 2020 |
| 3.0 | Июль 2018 | Июль 2020 |
| 3.1 | Сентябрь 2018 | Сентябрь 2020 |
| 3.2 | Ноябрь 2018 | Ноябрь 2020 |
| 3.3 | Январь 2019 | Январь 2021 |
| 3.4 | Март 2019 | Март 2021 |
| 3.5 | Май 2019 | Май 2021 |
| 3.6 | Август 2019 | Август 2021 |
| 3.7 | Ноябрь 2019 | Ноябрь 2021 |
| 3.8 | Февраль 2020 | Февраль 2022 |
| 3.9 | Май 2020 | Май 2022 |
| 4.0 | Август 2020 | Август 2022 |
Версия | Релиз | Окончание поддержки
-- | -- | --
2.8 | Март 2018 | Март 2020
2.9 | Май 2018 | Май 2020
3.0 | Июль 2018 | Июль 2020
3.1 | Сентябрь 2018 | Сентябрь 2020
3.2 | Ноябрь 2018 | Ноябрь 2020
3.3 | Январь 2019 | Январь 2021
3.4 | Март 2019 | Март 2021
3.5 | Май 2019 | Май 2021
3.6 | Август 2019 | Август 2021
3.7 | Ноябрь 2019 | Ноябрь 2021
3.8 | Февраль 2020 | Февраль 2022
3.9 | Май 2020 | Май 2022
4.0 | Август 2020 | Август 2022
Пакеты, которые существовали до ноября 2019 года, могут иметь более старые версии, которые явно помечены как совместимые с более старыми версиями Typescript; используйте тег "ts2.6" для Typescript 2.6, например.