跳至主要內容

no-inferrable-types

禁止對初始化為數字、字串或布林值的變數或參數進行顯式類型宣告。

🎨

擴展 "plugin:@typescript-eslint/stylistic" ESLint 配置 中啟用此規則。

🔧

此規則報告的一些問題可透過 --fix ESLint 命令列選項.

自動修復。TypeScript 能夠從參數、屬性和變數的預設值或初始值推斷其類型。無需在初始化為布林值、數字或字串的這些建構函式上使用顯式 : 類型註釋。這樣做會增加程式碼不必要的冗長性 - 使其難以閱讀 - 並且在某些情況下可能會阻止 TypeScript 推斷更具體的字面量類型(例如 10)而不是更通用的基本類型(例如 number)。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-inferrable-types": "error"
}
};

在 Playground 中試用此規則 ↗

範例

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) {}
在 Playground 中開啟

選項

此規則接受以下選項

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

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

ignoreParameters

設定為 true 時,以下模式視為有效

function foo(a: number = 5, b: boolean = true) {
// ...
}
在 Playground 中開啟

ignoreProperties

設定為 true 時,以下模式視為有效

class Foo {
prop: number = 5;
}
在 Playground 中開啟

何時不應使用

如果您強烈偏好具有顯式類型,而不管它們是否可以推斷,則此規則可能不適合您。

進一步閱讀

資源