Skip to content

方法签名

方法签名(Method Signature)是 TypeScript 中接口或类的一部分,用于定义对象的方法。它描述了方法的参数列表和返回值类型,但不提供具体实现。通过方法签名,你可以确保任何实现该接口的对象都提供了符合预期的方法。

方法签名的基本结构

一个方法签名由以下部分组成:

  1. 方法名称:标识符,用来命名方法。
  2. 参数列表:包括每个参数的名称和类型。
  3. 返回值类型:指定方法执行后返回的值的类型。

示例

typescript
interface ClockInterface {
  currentTime: Date;
  setTime(d: Date): void; // 方法签名
}

在这个例子中,ClockInterface 定义了一个名为 setTime 的方法签名,它接收一个 Date 类型的参数并返回 void(即没有返回值)。

方法签名与函数签名的区别

  • 函数签名:直接定义了一个可以被调用的函数的行为。

    typescript
    interface SearchFunc {
      (source: string, subString: string): boolean;
    }
  • 方法签名:定义了对象内部的一个方法的行为,通常作为接口或类的一部分。

    typescript
    interface ClockInterface {
      setTime(d: Date): void;
    }

方法签名的使用场景

方法签名主要用于以下几个方面:

  1. 接口定义:确保实现接口的对象提供了特定的方法。

    typescript
    interface Animal {
      makeSound(): void;
    }
    
    class Dog implements Animal {
      makeSound() {
        console.log("Bark");
      }
    }
  2. 类定义:为类中的方法提供类型信息,确保方法按照预期工作。

    typescript
    class Clock {
      currentTime: Date = new Date();
    
      setTime(d: Date): void {
        this.currentTime = d;
      }
    }
  3. 对象字面量:当你创建对象字面量时,可以使用方法签名来确保对象有特定的方法。

    typescript
    const obj: { greet(name: string): string } = {
      greet(name) {
        return `Hello, ${name}`;
      },
    };

方法签名的特性

  • 可选参数:可以在参数后面加上 ? 来标记该参数为可选。

    typescript
    interface Options {
      method(option?: string): void;
    }
  • 默认参数:可以为参数提供默认值,如果调用时没有提供该参数,则使用默认值。

    typescript
    interface Options {
      method(option: string = "default"): void;
    }
  • 剩余参数:使用 ... 操作符收集不定数量的参数为一个数组。

    typescript
    interface Calculator {
      add(...numbers: number[]): number;
    }
  • 只读属性:虽然不是方法签名的一部分,但在接口中可以定义只读属性,这些属性不能在实例化后被修改。

    typescript
    interface Point {
      readonly x: number;
      readonly y: number;
      moveBy(dx: number, dy: number): void;
    }

方法签名的实现

当我们在接口中定义了方法签名后,必须在实现该接口的类或对象中提供具体的方法实现。

实现接口中的方法签名

typescript
interface ClockInterface {
  currentTime: Date;
  setTime(d: Date): void;
}

class Clock implements ClockInterface {
  currentTime: Date = new Date();

  setTime(d: Date): void {
    this.currentTime = d;
  }

  // 可以添加额外的方法
  toString(): string {
    return this.currentTime.toString();
  }
}

实现对象字面量中的方法签名

typescript
const obj: { greet(name: string): string } = {
  greet(name) {
    return `Hello, ${name}`;
  },
};

console.log(obj.greet("Alice")); // 输出: Hello, Alice

总结

方法签名是 TypeScript 中确保代码类型安全的重要工具。它们允许你在接口、类或对象字面量中定义方法的行为,而不必立即提供具体的实现逻辑。理解如何正确使用方法签名可以帮助你编写出更加健壮和易于维护的代码。

Released under the MIT License.