Skip to main content

no-inferrable-types

Disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean.

🎨

ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic" 可启用此规则。

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复


TypeScript 能够根据参数、属性和变量的默认值或初始值推断其类型。 无需在初始化为布尔值、数字或字符串的这些构造之一上使用显式 : 类型注释。 这样做会给代码增加不必要的冗长 - 使其更难以阅读 - 并且在某些情况下可能会阻止 TypeScript 推断更具体的字面量类型(例如 10)而不是更一般的原始类型(例如 number

英:TypeScript is able to infer the types of parameters, properties, and variables from their default or initial values. There is no need to use an explicit : type annotation on one of those constructs initialized to a boolean, number, or string. Doing so adds unnecessary verbosity to code -making it harder to read- and in some cases can prevent TypeScript from inferring a more specific literal type (e.g. 10) instead of the more general primitive type (e.g. number)

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-inferrable-types": "error"
}
};
在线运行试试这个规则 ↗

示例

const a: bigint = 10n;
const a: bigint = BigInt(10);
const a: boolean = !0;
const a: boolean = Boolean(null);
const a: boolean = true;
const a: null = null;
const a: number = 10;
const a: number = Infinity;
const a: number = NaN;
const a: number = Number('1');
const a: RegExp = /a/;
const a: RegExp = new RegExp('a');
const a: string = `str`;
const a: string = String(1);
const a: symbol = Symbol('a');
const a: undefined = undefined;
const a: undefined = void someValue;

class Foo {
prop: number = 5;
}

function fn(a: number = 5, b: boolean = true) {}
Open in Playground

选项

ignoreParameters

当设置为 true 时,以下模式被视为有效:

英:When set to true, the following pattern is considered valid:

function foo(a: number = 5, b: boolean = true) {
// ...
}
Open in Playground

ignoreProperties

当设置为 true 时,以下模式被视为有效:

英:When set to true, the following pattern is considered valid:

class Foo {
prop: number = 5;
}
Open in Playground

何时不使用它

如果你强烈喜欢使用显式类型,无论是否可以推断它们,则此规则可能不适合你。

英:If you strongly prefer to have explicit types regardless of whether they can be inferred, this rule may not be for you.

进一步阅读

选项

该规则接受以下选项

type Options = [
{
ignoreParameters?: boolean;
ignoreProperties?: boolean;
},
];

const defaultOptions: Options = [
{ ignoreParameters: false, ignoreProperties: false },
];

资源