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)

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-inferrable-types": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

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

选项

该规则接受以下选项:

type Options = [
{
/** Whether to ignore function parameters. */
ignoreParameters?: boolean;
/** Whether to ignore class properties. */
ignoreProperties?: boolean;
},
];

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

¥Options

ignoreParameters

Whether to ignore function parameters. Default: false.

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

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

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

ignoreProperties

Whether to ignore class properties. Default: false.

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

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

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

何时不使用它

¥When Not To Use It

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

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

如果你使用 --isolatedDeclarations 编译器选项,则此规则不兼容。

¥If you use the --isolatedDeclarations compiler option, this rule is incompatible.

进一步阅读

¥Further Reading

'## 资源'