Skip to main content

常规

如何启用 @typescript-eslint 规则?

¥How do I turn on a @typescript-eslint rule?

首先,确保你已阅读文档并了解 ESLint 配置文件:

¥First make sure you've read the docs and understand ESLint configuration files:

我们的 规则文档 详细说明了 "选项" 标题下每个规则支持的选项。我们使用 TypeScript 类型来描述规则的 Options 元组类型,你可以使用它来配置规则。在你的配置文件中,rules 对象的键是你希望配置的规则的名称,值遵循以下形式:

¥Our rule docs detail the options each rule supports under the "Options" heading. We use TypeScript types to describe an Options tuple type for the rule which you can use to configure the rule. In your config file the keys of the rules object are the names of the rules you wish to configure and the values follow the following form:

type Severity = 'off' | 'warn' | 'error';
type RuleConfig =
| Severity
| [Severity]
| [
Severity,
// Options is the tuple type from the rule docs
...Options,
];

一些例子

¥Some examples

eslint.config.mjs
export default tseslint.config(
// ... the rest of your config ...
{
rules: {
// turns a rule on with no configuration (i.e. uses the default configuration)
'@typescript-eslint/array-type': 'error',
// turns on a rule with configuration
'@typescript-eslint/no-explicit-any': ['warn', { ignoreRestArgs: true }],
},
},
);

如何禁止 <specific language feature>

¥How can I ban <specific language feature>?

ESLint 核心包含规则 no-restricted-syntax。此通用规则允许你为要禁止的代码指定 selector,以及自定义错误消息。

¥ESLint core contains the rule no-restricted-syntax. This generic rule allows you to specify a selector for the code you want to ban, along with a custom error message.

你可以使用 AST 可视化工具(例如左侧边栏上的 typescript-eslint 在线运行 > Options > AST Explorer),通过选择 ESTree 来帮助确定要禁止的 AST 的结构。

¥You can use an AST visualization tool such as typescript-eslint playground > Options > AST Explorer on its left sidebar by selecting ESTree to help in figuring out the structure of the AST that you want to ban.

Banning confusing property uses
{
"rules": {
"no-restricted-syntax": [
"error",

// Ban accessing `constructor.name`:
{
"selector": "MemberExpression[object.property.name='constructor'][property.name='name']",
"message": "'constructor.name' is not reliable after code minifier usage.",
},

// Ban get and set accessors:
{
"selector": "Property:matches([kind = \"get\"], [kind = \"set\"]), MethodDefinition:matches([kind = \"get\"], [kind = \"set\"])",
"message": "Don't use get and set accessors.",
},
],
},
}
Banning specific uses of class properties
{
"rules": {
"no-restricted-syntax": [
"error",

// Ban `private` members:
{
"selector": ":matches(PropertyDefinition, MethodDefinition)[accessibility=\"private\"]",
"message": "Use `#private` members instead.",
},

// Ban `#private` members:
{
"selector": ":matches(PropertyDefinition, MethodDefinition) > PrivateIdentifier.key",
"message": "Use the `private` modifier instead.",
},

// Ban static `this`:
{
"selector": "MethodDefinition[static = true] ThisExpression",
"message": "Prefer using the class's name directly.",
},
],
},
}
Banning specific uses of TypeScript enums
{
"rules": {
"no-restricted-syntax": [
"error",

// Ban all enums:
{
"selector": "TSEnumDeclaration",
"message": "My reason for not using any enums at all.",
},

// Ban just `const` enums:
{
"selector": "TSEnumDeclaration[const=true]",
"message": "My reason for not using const enums.",
},

// Ban just non-`const` enums:
{
"selector": "TSEnumDeclaration:not([const=true])",
"message": "My reason for not using non-const enums.",
},
],
},
}
Banning specific uses of TypeScript tuples
{
"rules": {
"no-restricted-syntax": [
"error",
// enforce tuple members have labels
{
"selector": "TSTupleType > :not(TSNamedTupleMember)",
"message": "All tuples should have labels.",
},
],
},
}

如何检查安装了哪些版本?

¥How do I check to see what versions are installed?

如果你有我们工具的多个版本,可能会导致各种错误。这是因为 ESLint 可能会根据你的运行方式每次运行时加载不同的版本 - 导致不一致的 lint 结果。

¥If you have multiple versions of our tooling, it can cause various bugs for you. This is because ESLint may load a different version each run depending on how you run it - leading to inconsistent lint results.

在项目的根目录中安装我们的工具并不意味着只安装一个版本。你的一个或多个依赖可能对我们的工具有自己的依赖,这意味着 npm/yarn 将另外安装该版本供该包使用。例如,react-scriptscreate-react-app 的一部分)依赖于我们的工具。

¥Installing our tooling in the root of your project does not mean that only one version is installed. One or more of your dependencies may have its own dependency on our tooling, meaning npm/yarn will additionally install that version for use by that package. For example, react-scripts (part of create-react-app) has a dependency on our tooling.

你可以使用以下命令检查项目中安装的版本:

¥You can check what versions are installed in your project using the following commands:

npm list @typescript-eslint/eslint-plugin @typescript-eslint/parser

如果你看到安装了多个版本,那么你必须使用 Yarn 解析 强制使用单个版本,或者你必须降级根版本以匹配依赖版本。

¥If you see more than one version installed, then you will have to either use yarn resolutions to force a single version, or you will have to downgrade your root versions to match the dependency versions.

在这种情况下,最好的做法是等到你的依赖发布支持我们最新版本的新版本。

¥The best course of action in this case is to wait until your dependency releases a new version with support for our latest versions.

在我的 IDE 中对其他文件进行 linting 时,不会反映对一个文件的更改

¥Changes to one file are not reflected when linting other files in my IDE

tl;dr:重新启动 ESLint 服务器以强制更新。

¥tl;dr: Restart your ESLint server to force an update.

当磁盘上的任意文件发生更改时,ESLint 目前没有任何方法告诉解析器(例如我们的解析器)。这意味着如果你更改文件 B 导入的文件 A,它不会更新文件 B 的 lint 缓存 - 即使文件 B 的文本内容已更改。有时,唯一的解决方案是完全重新启动 ESLint 编辑器扩展。

¥ESLint currently does not have any way of telling parsers such as ours when an arbitrary file is changed on disk. That means if you change file A that is imported by file B, it won't update lint caches for file B -- even if file B's text contents have changed. Sometimes the only solution is to restart your ESLint editor extension altogether.

有关更多信息,请参阅 问题评论

¥See this issue comment for more information.

提示

VS Code 的 ESLint 扩展 提供 ESLint: Restart ESLint Server 操作。

¥VS Code's ESLint extension provides an ESLint: Restart ESLint Server action.

我收到 no-unsafe-* 条关于跨文件更改的投诉

¥I get no-unsafe-* complaints for cross-file changes

参见 对一个文件的更改不会反映在我的 IDE 中对其他文件进行 linting 中no-unsafe-argumentno-unsafe-assignmentno-unsafe-call 等规则经常受到影响。

¥See Changes to one file are not reflected in linting other files in my IDE. Rules such as no-unsafe-argument, no-unsafe-assignment, and no-unsafe-call are often impacted.

typescript-eslint 与原生速度 linters 相比如何?

¥How does typescript-eslint compare to native-speed linters?

Biome linterDeno linteroxlint 等 "原生速度" linters 可以在非常快的语言(如 Go 或 Rust)中运行,因此在非类型感知 linting 中通常可以比 ESLint 运行得快得多。它们还可以更轻松地配置,因为它们不需要支持 ESLint 的完整生态系统和旧版路径。

¥"Native-speed" linters such as Biome linter, Deno linter, and oxlint run in very fast languages such as Go or Rust, and so can generally run significantly faster than ESLint in non-type-aware-linting. They can also be easier to configure because they don't need to support the full ecosystem and legacy trail of ESLint.

但是,在它们支持 类型化的 linting 之前,它们并不是 typescript-eslint 的完全替代品。如果你打算使用它们,我们推荐 "双重 linting":使用这些 linters 来支持它们,然后在并行或第二步中添加 ESLint 进行类型 linting。我们的 *-type-checked-only 共享配置 将在你的 ESLint 配置中仅启用类型检查规则。

¥However, until they support typed linting, they aren't a full replacement for typescript-eslint. If you plan on using them, we recommend "dual linting": using those linters for what they support, then adding in ESLint for typed linting in a parallel or second step. Our *-type-checked-only Shared Configs will enable only type-checked rules in your ESLint config.

例如,以下配置仅启用推荐配置的类型检查规则和 recommendedTypeCheckedOnly

¥For example, the following config enables only the recommended config's type-checked rules with recommendedTypeCheckedOnly:

eslint.config.mjs
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default tseslint.config(
tseslint.configs.recommendedTypeCheckedOnly,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
);

例如,oxlint 的集成 > ESLint 文档 描述了如何关闭 oxlint 已经支持的 ESLint 规则。

¥For example, oxlint's Integration > ESLint documentation describes how to turn off ESLint rules that are already supported by oxlint.

“‘<key>’ 属性在‘<type>’ 节点上已弃用。改用“<key>”。警告

¥"The '<key>' property is deprecated on '<type>' nodes. Use '<key>' instead." warnings

如果你看到此警告,则可能你正在使用尚未针对 typescript-eslint v6 进行更新的 ESLint 插件(或其他工具)。确保你使用的是每个 ESLint 插件(和其他工具)的最新版本。

¥If you're seeing this warning, it's likely you're using an ESLint plugin (or other tooling) that hasn't been updated for typescript-eslint v6. Make sure you're using the latest versions of each of your ESLint plugins (and other tooling).

如果你使用了许多 ESLint 插件,并且已将每个插件更新到最新版本,但不确定这个投诉来自哪一个,请尝试以下任一或两者:

¥If you're using many ESLint plugins, have updated each to their latest version, and you're not sure which one this complaint is coming from, try either or both of:

  • 使用 --trace-deprecation(例如 npx cross-env NODE_OPTIONS=--trace-deprecation npm run lint)运行

    ¥Running with --trace-deprecation (e.g. npx cross-env NODE_OPTIONS=--trace-deprecation npm run lint)

  • 一次禁用其中一半以缩小其所属插件的范围

    ¥Disabling half of them at a time to narrow down which plugin it is

然后确保每个插件都有一个 GitHub 问题,要求他们发布支持 typescript-eslint v6 的版本。

¥Then make sure each of those plugins has a GitHub issue asking that they release a version supporting typescript-eslint v6.

提示

对于在仍需要支持 typescript-eslint v5 的插件中更新 ESLint 规则的开发者:如果新属性键不存在,你可能需要 || 回退到旧属性键:

¥For developers updating ESLint rules in plugins that still need to support typescript-eslint v5: you may need to || fall back to the old property key if the new one doesn't exist:

- node.typeParameters
+ node.typeArguments || node.typeParameters

有关更多上下文,请参阅 一些名为 typeParameters 而不是 typeArguments 的属性 问题和实现 修复:在需要时将 typeParameters 重命名为 typeArguments 拉取请求。

¥For more context, see the Some properties named typeParameters instead of typeArguments issue, and the implementing fix: rename typeParameters to typeArguments where needed pull request.

typescript-eslint v6 发布帖子 在 typescript-eslint v6 上有更多信息。

¥The typescript-eslint v6 release post has more information on typescript-eslint v6.

我的 linting 感觉非常慢

¥My linting feels really slow

如果你认为你遇到了性能问题,请参阅我们的 性能故障排除文档

¥If you think you're having issues with performance, see our Performance Troubleshooting documentation.