使用代码库时,TypeScript 中的类型系统具有不同级别的严格性:
🌐 The type system in TypeScript has different levels of strictness when working with a codebase:
- 仅基于 JavaScript 代码推断的类型系统
- 通过 JSDoc 在 JavaScript 中进行增量类型化
- 在 JavaScript 文件中使用
// @ts-check - TypeScript 代码
- 启用
strict的 TypeScript
每一步都代表朝着更安全的类型系统迈进,但并非每个项目都需要那种级别的验证。
🌐 Each step represents a move towards a safer type-system, but not every project needs that level of verification.
使用 JavaScript 的 TypeScript
🌐 TypeScript with JavaScript
这是指你使用一个编辑器,它使用 TypeScript 提供工具功能,比如自动补齐、跳转到符号以及重构工具(如重命名)。 主页 上有一个列出带有 TypeScript 插件的编辑器的列表。
🌐 This is when you use an editor which uses TypeScript to provide tooling like auto-complete, jump to symbol and refactoring tools like rename. The homepage has a list of editors which have TypeScript plugins.
通过 JSDoc 在 JS 中提供类型提示
🌐 Providing Type Hints in JS via JSDoc
在 .js 文件中,类型通常可以被推断出来。当类型无法推断时,可以使用 JSDoc 语法来指定。
🌐 In a .js file, types can often be inferred. When types can’t be inferred, they can be specified using JSDoc syntax.
在声明之前的 JSDoc 注释将用于设置该声明的类型。例如:
🌐 JSDoc annotations that come before a declaration will be used to set the type of that declaration. For example:
jsTry/** @type {number} */varx ;x = 0; // OKx = false; // OK?!
你可以在 JSDoc 支持的类型 中找到支持的 JSDoc 模式的完整列表。
🌐 You can find the full list of supported JSDoc patterns in JSDoc Supported Types.
@ts-check
前一个代码示例的最后一行在 TypeScript 中会引发错误,但在默认的 JavaScript 项目中不会。要在你的 JavaScript 文件中启用错误检测,请在你的 .js 文件的第一行添加 // @ts-check,让 TypeScript 将其视为错误。
🌐 The last line of the previous code sample would raise an error in TypeScript, but it doesn’t by default in a JS project.
To enable errors in your JavaScript files add: // @ts-check to the first line in your .js files to have TypeScript raise it as an error.
jsTry// @ts-check/** @type {number} */varx ;x = 0; // OKType 'boolean' is not assignable to type 'number'.2322Type 'boolean' is not assignable to type 'number'.= false; // Not OK x
如果你有很多 JavaScript 文件想要添加错误,那么你可以改用 jsconfig.json。
你可以通过在文件中添加 // @ts-nocheck 注释来跳过检查某些文件。
🌐 If you have a lot of JavaScript files you want to add errors to then you can switch to using a jsconfig.json.
You can skip checking some files by adding a // @ts-nocheck comment to files.
TypeScript 可能会给你一些你不同意的错误,在这种情况下,你可以通过在前一行添加 // @ts-ignore 或 // @ts-expect-error 来忽略特定行的错误。
🌐 TypeScript may offer you errors which you disagree with, in those cases you can ignore errors on specific lines by adding // @ts-ignore or // @ts-expect-error on the preceding line.
jsTry// @ts-check/** @type {number} */varx ;x = 0; // OK// @ts-expect-errorx = false; // Not OK
想了解更多关于 TypeScript 如何解释 JavaScript 的信息,请阅读 TypeScript 如何对 JavaScript 进行类型检查
🌐 To learn more about how JavaScript is interpreted by TypeScript read How TS Type Checks JS