禁止不安全的回傳
不允許傳回類型為
any
的函式。
✅
擴充 "plugin:@typescript-eslint/建議類型檢查"
在 ESLint 設定檔 啟用此規則。
💭
此規則需要 類型資訊 才能執行。
TypeScript 中的 any
類型是一種從類型系統中逃逸的危險「後門」。使用 any
會停用許多類型檢查規則,通常只在最後手段或建立雛型程式碼時使用。
儘管您有最好的意圖,any
類型有時可能會出現在您的程式碼庫中。傳回 any
型別值表示你的程式碼庫可能產生類型安全漏洞並造成錯誤。
此規則不允許從函式回傳 any
或 any[]
。
此規則也會比較泛型型態引數型態,確保您不會在泛型位置傳回不安全的 any
給預期特定型態的函式。例如,如果您從宣告為傳回 Set<string>
的函式傳回 Set<any>
,會產生錯誤。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-return": "error"
}
};
在遊樂場中嘗試此規則↗
範例
- ❌ 錯誤
- ✅ 正確
function foo1() {
return 1 as any;
}
function foo2() {
return Object.create(null);
}
const foo3 = () => {
return 1 as any;
};
const foo4 = () => Object.create(null);
function foo5() {
return [] as any[];
}
function foo6() {
return [] as Array<any>;
}
function foo7() {
return [] as readonly any[];
}
function foo8() {
return [] as Readonly<any[]>;
}
const foo9 = () => {
return [] as any[];
};
const foo10 = () => [] as any[];
const foo11 = (): string[] => [1, 2, 3] as any[];
// generic position examples
function assignability1(): Set<string> {
return new Set<any>([1]);
}
type TAssign = () => Set<string>;
const assignability2: TAssign = () => new Set<any>([true]);
在遊樂場中開啟function foo1() {
return 1;
}
function foo2() {
return Object.create(null) as Record<string, unknown>;
}
const foo3 = () => [];
const foo4 = () => ['a'];
function assignability1(): Set<string> {
return new Set<string>(['foo']);
}
type TAssign = () => Set<string>;
const assignability2: TAssign = () => new Set(['foo']);
在遊樂場中開啟在某些情況下,此規則允許將 any
傳回給 unknown
。
允許傳回 any
給 unknown
的範例
function foo1(): unknown {
return JSON.parse(singleObjString); // Return type for JSON.parse is any.
}
function foo2(): unknown[] {
return [] as any[];
}
在遊樂場中開啟選項
此規則不可設定。
不使用此規則的時機
如果您的程式碼庫中有許多現有的 any
或不安全的程式碼區域,可能很難啟用此規則。在提高專案不安全區域的型態安全性之前,可能會比較容易略過 no-unsafe-*
規則。您可以考慮使用 ESLint 禁止註解 來取代完全停用此規則,特別針對特定的情況。
相關性
型態檢查的細查規則比傳統的細查規則更強大,但也需要設定 型態檢查細查。如果您在啟用型態檢查規則後遇到效能降低的情況,請參閱 效能疑難排解。