no-empty-function
不允許空函式。
🎨
延伸 "plugin:@typescript-eslint/風格"
在 ESLint 組態 啟用這項規則。
這項規則延伸基礎的 eslint/no-empty-function
規則。它增強支援處理 TypeScript 特定的程式碼,否則程式碼觸發規則。
一個有效的 TypeScript 特定程式碼範例,否則將觸發 no-empty-function
規則是,在建構函數中使用 參數屬性。
如何使用
.eslintrc.cjs
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"no-empty-function": "off",
"@typescript-eslint/no-empty-function": "error"
}
};
在遊樂場中嘗試這項規則 ↗
選項
請參閱 eslint/no-empty-function
選項。
這項規則新增下列選項
type AdditionalAllowOptionEntries =
| 'private-constructors'
| 'protected-constructors'
| 'decoratedFunctions'
| 'overrideMethods';
type AllowOptionEntries =
| BaseNoEmptyFunctionAllowOptionEntries
| AdditionalAllowOptionEntries;
interface Options extends BaseNoEmptyFunctionOptions {
allow?: Array<AllowOptionEntries>;
}
const defaultOptions: Options = {
...baseNoEmptyFunctionDefaultOptions,
allow: [],
};
允許:private-constructors
針對選項 { "allow": ["private-constructors"] }
編寫正確程式碼範例
class Foo {
private constructor() {}
}
在 Playground 中開啟允許:protected-constructors
針對選項 { "allow": ["protected-constructors"] }
編寫正確程式碼範例
class Foo {
protected constructor() {}
}
在 Playground 中開啟允許:decoratedFunctions
針對選項 { "allow": ["decoratedFunctions"] }
編寫正確程式碼範例
class Foo {
@decorator()
foo() {}
}
在 Playground 中開啟允許:overrideMethods
針對選項 { "allow": ["overrideMethods"] }
編寫正確程式碼範例
abstract class Base {
protected greet(): void {
console.log('Hello!');
}
}
class Foo extends Base {
protected override greet(): void {}
}
在 Playground 中開啟什麼時候不使用
如果您使用外部 API,而 API 需要函式,即使它們不執行任何動作,您可能會想避免這個規則。您可以考慮在特定情況下使用 ESLint 禁用註解,而非完全停用這項規則。
測試程式碼也時常違反這項規則。如果您的測試設定不支援「模擬」或「間諜」函式,例如 jest.fn()
、sinon.spy()
或 vi.fn()
,您可能希望在測試檔案中停用這項規則。同樣,如果這些情況並非非常常見,您可以考慮在特定情況下使用 ESLint 禁用註解,而非在測試檔案中完全停用這項規則。