restrict-plus-operands
要求加法的兩個操作元都是相同的類型,並且必須是
bigint
、number
或string
。
✅
擴充 "plugin:@typescript-eslint/recommended-type-checked"
中的 ESLint 配置 可啟用此規則。
💭
此規則需要 類型資訊 才能執行。
TypeScript 允許使用 +
將任何類型(們)的兩個值加起來。然而,加總不同類型和/或非原始類型的值經常表示程式設計師發生錯誤。
當 +
營運結合兩種不同類型的值,或類型不是 bigint
、number
或 string
時,此規則會進行報告。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/restrict-plus-operands": "error"
}
};
在遊戲區中試試此規則▶
範例
- ❌ 錯誤
- ✅ 正確
選項
此規則接受下列選項,並在 strict
和 strict-type-checked
配置中具有更嚴格的設定。
type Options = [
{
/** Whether to allow `any` typed values. */
allowAny?: boolean;
/** Whether to allow `boolean` typed values. */
allowBoolean?: boolean;
/** Whether to allow potentially `null` or `undefined` typed values. */
allowNullish?: boolean;
/** Whether to allow `bigint`/`number` typed values and `string` typed values to be added together. */
allowNumberAndString?: boolean;
/** Whether to allow `regexp` typed values. */
allowRegExp?: boolean;
/** Whether to skip compound assignments such as `+=`. */
skipCompoundAssignments?: boolean;
},
];
const defaultOptionsRecommended: Options = [
{
allowAny: true,
allowBoolean: true,
allowNullish: true,
allowNumberAndString: true,
allowRegExp: true,
skipCompoundAssignments: false,
},
];
// These options are merged on top of the recommended defaults
const defaultOptionsStrict: Options = [
{
allowAny: false,
allowBoolean: false,
allowNullish: false,
allowNumberAndString: false,
allowRegExp: false,
},
];
注意
我們通常建議不要使用這些選項,因為它們限制了可以檢查哪種不正確的 +
使用方式。這反過來會嚴重限制規則可以執行的驗證,以確保產生的字串和數字正確。
使用 allow*
選項的安全替代方案包括
- 使用記錄 API 的變形形式,以避免需要
+
值。console.log('The result is ' + true);
console.log('The result is', true); - 使用
.toFixed()
將數字強制轉換為格式良好的字串表示形式const number = 1.123456789;
const result = 'The number is ' + number.toFixed(2);
// result === 'The number is 1.12' - 對其他類型呼叫
.toString()
,標示顯式和有意的字串強制轉換const arg = '11';
const regex = /[0-9]/;
const result =
'The result of ' +
regex.toString() +
'.test("' +
arg +
'") is ' +
regex.test(arg).toString();
// result === 'The result of /[0-9]/.test("11") is true'
allowAny
使用 { allowAny: true }
的此規則的程式碼範例
- ❌ 錯誤
- ✅ 正確
allowBoolean
使用 { allowBoolean: true }
的此規則的程式碼範例
- ❌ 錯誤
- ✅ 正確
allowNullish
使用 { allowNullish: true }
的此規則的程式碼範例
- ❌ 錯誤
- ✅ 正確
let fn = (a: number, b: unknown) => a + b;
let fn = (a: number, b: never) => a + b;
let fn = (a: string, b: unknown) => a + b;
let fn = (a: string, b: never) => a + b;
在遊樂場中開啟let fn = (a: number, b: undefined) => a + b;
let fn = (a: number, b: null) => a + b;
let fn = (a: string, b: undefined) => a + b;
let fn = (a: string, b: null) => a + b;
在遊樂場中開啟allowNumberAndString
使用 { allowNumberAndString: true }
的此規則的程式碼範例
- ❌ 錯誤
- ✅ 正確
allowRegExp
使用 { allowRegExp: true }
的此規則的程式碼範例
- ❌ 錯誤
- ✅ 正確
skipCompoundAssignments
使用 { skipCompoundAssignments: false }
的此規則的程式碼範例
- ❌ 錯誤
- ✅ 正確
何時不使用
如果您不介意值中有 "[object Object]"
或不正確的類型強制轉換的風險,那麼您就不需要這條規則。
相關
進一步閱讀
經過型別驗證的 linter 規則比傳統的 linter 規則更為強大,但需要設定經過型別驗證的 linting。在啟用經過型別驗證的規則後,如果效能下降,請參閱效能疑難排解。