📝 调用签名
接口可以描述函数类型,称为调用签名。
// 定义函数类型接口
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!