跳到主要內容

避免命名空間

禁止 TypeScript 命名空間。

歷史上,TypeScript 允許一種稱為「自訂模組」(module Example {}) 的程式碼組織形式,後來更名為「命名空間」(namespace Example)。命名空間是一種過時的 TypeScript 程式碼組織方式。現在建議使用 ES2015 模組語法 (import/export)。

此規則不會回報使用 TypeScript 模組宣告描述外部 API (declare module 'foo' {}) 的情況。

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

在測試場中嘗試此規則 ↗

範例

使用預設選項的程式碼範例

module foo {}
namespace foo {}

declare module foo {}
declare namespace foo {}
在測試場中開啟

選項

本規則接受以下選項

type Options = [
{
/** Whether to allow `declare` with custom TypeScript namespaces. */
allowDeclarations?: boolean;
/** Whether to allow `declare` with custom TypeScript namespaces inside definition files. */
allowDefinitionFiles?: boolean;
},
];

const defaultOptions: Options = [
{ allowDeclarations: false, allowDefinitionFiles: true },
];

allowDeclarations

選項 { "allowDeclarations": true } 範例程式碼

module foo {}
namespace foo {}
在測試場中開啟

選項 { "allowDeclarations": false } 範例程式碼

module foo {}
namespace foo {}
declare module foo {}
declare namespace foo {}
在測試場中開啟

allowDefinitionFiles

選項 { "allowDefinitionFiles": true } 範例程式碼

// if outside a d.ts file
module foo {}
namespace foo {}

// if outside a d.ts file and allowDeclarations = false
module foo {}
namespace foo {}
declare module foo {}
declare namespace foo {}
在測試場中開啟

何時不使用

如果你的專案是在現代模組和命名空間之前建置,那麼可能很難跳脫命名空間。這種情況下,你可能無法將此規則用於專案的各個部分。你可以考慮針對這些特定情況使用 ESLint 禁止註解,而非完全停用這條規則。

延伸閱讀

資源