🎯 学习目标

  • 掌握函数类型接口的定义
  • 理解调用签名和构造签名
  • 学会定义函数类型的属性
  • 了解函数重载与接口

📝 调用签名

接口可以描述函数类型,称为调用签名

// 定义函数类型接口 interface SearchFunc { (source: string, subString: string): boolean; } // 使用函数类型接口 const mySearch: SearchFunc = function(src, sub) { return src.indexOf(sub) !== -1; }; // 使用箭头函数 const search: SearchFunc = (source, subString) => { return source.includes(subString); }; // 调用 console.log(search('hello world', 'world')); // true
💡
参数名称

函数类型接口中的参数名称不需要与实际实现一致,只要类型匹配即可。

🔧 接口中的方法

interface Counter { count: number; increment(): void; // 方法签名 decrement(): void; reset(count: number): void; } // 实现接口 const counter: Counter = { count: 0, increment() { this.count++; }, decrement() { this.count--; }, reset(count: number) { this.count = count; } }; counter.increment(); counter.increment(); counter.decrement(); console.log(counter.count); // 1

🏗️ 构造签名

// 构造签名:使用 new 关键字 interface AnimalConstructor { new (name: string): Animal; } interface Animal { name: string; speak(): void; } class Dog implements Animal { constructor(public name: string) {} speak() { console.log(`${this.name} says Woof!`); } } // 工厂函数 function createAnimal(ctor: AnimalConstructor, name: string): Animal { return new ctor(name); } const dog = createAnimal(Dog, 'Buddy'); dog.speak(); // Buddy says Woof!

📝 本节小结

  • • 调用签名:interface Fn { (args): ReturnType }
  • • 构造签名:interface Ctor { new (args): Type }
  • • 接口中可定义方法签名
  • • 参数名称不必与实现一致