consistent-type-exports
強制一致使用類型匯出。
🔧
此規則報告的一些問題可由 --fix
ESLint 命令列選項自動修復。.
💭
此規則需要 類型資訊 來執行。
TypeScript 允許在匯出上指定 type
關鍵字,以指出匯出僅存在於類型系統中,而不是在執行時期。這允許轉譯器在不知道依賴項的類型的情況下刪除匯出。
請參閱 部落格 > 一致的類型匯出和匯入:原因和方法 以取得更多詳細資訊。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/consistent-type-exports": "error"
}
};
在遊樂場中嘗試這一規則 ↗
範例
- ❌ 錯誤
- ✅ 正確
interface ButtonProps {
onClick: () => void;
}
class Button implements ButtonProps {
onClick = () => console.log('button!');
}
export { Button, ButtonProps };
在遊樂場中開啟interface ButtonProps {
onClick: () => void;
}
class Button implements ButtonProps {
onClick = () => console.log('button!');
}
export { Button };
export type { ButtonProps };
在遊樂場中開啟選項
此規則接受下列選項
type Options = [
{
fixMixedExportsWithInlineTypeSpecifier?: boolean;
},
];
const defaultOptions: Options = [
{ fixMixedExportsWithInlineTypeSpecifier: false },
];
fixMixedExportsWithInlineTypeSpecifier
當將此設定為 true,該規則會使用 TS 4.5 的「內嵌式類型指定項」自動修復「混合式」匯出的狀況。如果您使用的 TypeScript 版本低於 4.5,則無法使用此選項。
例如,以下程式碼
const x = 1;
type T = number;
export { x, T };
搭配 {fixMixedExportsWithInlineTypeSpecifier: true}
會修復成
const x = 1;
type T = number;
export { x, type T };
搭配 {fixMixedExportsWithInlineTypeSpecifier: false}
會修復成
const x = 1;
type T = number;
export type { T };
export { x };
何時不要使用它
如果您使用 --isolatedModules
,則如果不使用 export type
重新匯出類型,編譯器會出錯。這種情況下,該規則可能比較不實用。
如果您特別想因為風格考量而同時使用兩種匯出類別,或不想強制作為單一風格,您可以避免使用此規則。
但是,請注意樣式不一致會影響專案的可讀性。我們建議為專案選擇此規則最合適的單一選項。
類型檢查後的校正規則比傳統的校正規則強大,但也需要設定 類型檢查的校正。如果您在啟用類型檢查的規則後遇到效能下降,請參閱效能問題排除。