跳至主要內容

method-signature-style

強制使用特定方法簽章語法。

TypeScript 提供兩種方法定義物件/介面函數屬性

interface Example {
// method shorthand syntax
func(arg: string): number;

// regular property with function type
func: (arg: string) => number;
}

這兩者非常相似;大多數時候使用哪一個沒關係。

一個好的作法是使用 TypeScript 的 strict 選項(暗示 strictFunctionTypes),可僅針對函數屬性啟用正確的型別檢查(方法簽章取得舊行為)。

TypeScript 常見問答

同類型的方法和函數屬性行為不同。方法在其參數中總是二變異的,而函數屬性在其參數中在 strictFunctionTypes 下是反變異的。

請在 TypeScript PR 針對編譯器選項,了解此背後的理由。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/method-signature-style": "error"
}
};

在遊戲場中嘗試此規則 ↗

選項

此規則接受下列選項

type Options = ['method' | 'property'];

const defaultOptions: Options = ['property'];

此規則接受一個字串選項

  • "property":強制使用 property 簽章函數。結合 TypeScript 的嚴格模式使用此選項,以強制執行最大程度的正確性。
  • "method":強制使用 method 簽章函數。如果您沒有使用 TypeScript 的嚴格模式,而且偏好此樣式,請使用此選項。

預設為 "property"

property

使用 property 選項的範例程式碼。

interface T1 {
func(arg: string): number;
}
type T2 = {
func(arg: boolean): void;
};
interface T3 {
func(arg: number): void;
func(arg: string): void;
func(arg: boolean): void;
}
在遊戲場中開啟

method

使用 method 選項的範例程式碼。

interface T1 {
func: (arg: string) => number;
}
type T2 = {
func: (arg: boolean) => void;
};
在遊戲場中開啟

何時不使用

如果您不想強制執行特定物件/介面函數類型的樣式,或者如果您沒有使用 strictFunctionTypes,則您不需要此規則。

但是,請記住不一致的樣式會影響專案的可讀性。我們建議為此規則選擇最適合您專案的單一選項。

資源