跳到內容

typescript/prefer-function-type 風格

🛠️ 此規則的部分違規情況可使用自動修正。

功能說明

強制使用函式類型而不是具有呼叫簽名的介面。 TypeScript 允許兩種常見的方式來宣告函式的類型

  • 函式類型:() => string
  • 具有簽名的物件類型:{ (): string }

函式類型形式通常更簡潔,因此在可能的情況下會優先使用。

此規則建議使用函式類型,而不是具有單個呼叫簽名的介面或物件類型字面值。

範例

ts
// error
interface Example {
  (): string;
}

function foo(example: { (): number }): number {
  return example();
}

interface ReturnsSelf {
  (arg: string): this;
}

// success
type Example = () => string;

function foo(example: () => number): number {
  return bar();
}

// returns the function itself, not the `this` argument.
type ReturnsSelf = (arg: string) => ReturnsSelf;

function foo(bar: { (): string; baz: number }): string {
  return bar();
}

interface Foo {
  bar: string;
}
interface Bar extends Foo {
  (): void;
}

// multiple call signatures (overloads) is allowed:
interface Overloaded {
  (data: string): number;
  (id: number): string;
}
// this is equivalent to Overloaded interface.
type Intersection = ((data: string) => number) & ((id: number) => string);

參考

在 MIT 許可下發布。