no-unsafe-argument
不允許用具有
any
型別值的函式呼叫函式。
💭
此規則需要 型別資訊 才能執行。
TypeScript 中的 any
型別是一個從型別系統中逃脫出來的危險「途徑」。使用 any
會停用許多型別檢查規則,通常只能作為最後的手段或在建立原型程式碼時使用。
儘管你已盡力,但 any
型別有時還是會滲入你的程式碼庫。用 any
型別參數呼叫函式會產生潛在的安全漏洞和錯誤來源。
此規則不允許呼叫參數中包含 any
的函式。其中包括將包含 any
型別元素的陣列或組散布為函式參數。
這個規則也會比較泛型類型引數類型,以確保您不會在接收函式中將不安全的any
傳遞到泛型位置,而接收函式需要特定類型。例如,如果您將Set<any>
作為引數傳遞到宣告為Set<string>
的參數,將會產生錯誤。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-argument": "error"
}
};
在展示區嘗試這個規則 ↗
範例
- ❌ 錯誤
- ✅ 正確
declare function foo(arg1: string, arg2: number, arg3: string): void;
const anyTyped = 1 as any;
foo(...anyTyped);
foo(anyTyped, 1, 'a');
const anyArray: any[] = [];
foo(...anyArray);
const tuple1 = ['a', anyTyped, 'b'] as const;
foo(...tuple1);
const tuple2 = [1] as const;
foo('a', ...tuple, anyTyped);
declare function bar(arg1: string, arg2: number, ...rest: string[]): void;
const x = [1, 2] as [number, ...number[]];
foo('a', ...x, anyTyped);
declare function baz(arg1: Set<string>, arg2: Map<string, string>): void;
foo(new Set<any>(), new Map<any, string>());
在展示區開啟declare function foo(arg1: string, arg2: number, arg3: string): void;
foo('a', 1, 'b');
const tuple1 = ['a', 1, 'b'] as const;
foo(...tuple1);
declare function bar(arg1: string, arg2: number, ...rest: string[]): void;
const array: string[] = ['a'];
bar('a', 1, ...array);
declare function baz(arg1: Set<string>, arg2: Map<string, string>): void;
foo(new Set<string>(), new Map<string, string>());
在展示區開啟規則允許將 any
引數傳遞到 unknown
的情況的確存在。
允許的 any
至 unknown
指定範例
declare function foo(arg1: unknown, arg2: Set<unknown>, arg3: unknown[]): void;
foo(1 as any, new Set<any>(), [] as any[]);
在展示區開啟選項
這個規則無法設定。
什麼時候不應使用它
如果您的程式碼範例有許多現有的 any
或不安全程式碼區域,啟用此規則可能會很困難。在專案的不安全區域加強類型安全時,可能會比較容易略過 no-unsafe-*
規則。您可以考慮對特定情況使用 ESLint 禁用註解,而不是完全停用這項規則。
相關資訊
類型檢查的動態程式碼規則比傳統的動態程式碼規則更強大,但需要設定 類型檢查的動態程式碼檢查。如果在啟用類型檢查規則後發現效能降低,請參閱 效能問題解決。