1.约定函数的参数
function eat(food: string) {
return `${food} is very delicious!`;
}
2.约定函数的参数和返回值
function eat(food: string): string {
return `${food} is very delicious!`;
}
3.函数返回多个值(元祖)
function walk(distance: string): [string, number] {
return [`${distance} is very far!`, 1];
}
4.函数类型的接口
interface Person {
eat: Eat; // 接口嵌套定义
walk?(a: number): boolean; // 直接定义
}
interface Eat {
(food: string, drink: string, fruit?: string): string;
}
// 函数类型接口的实现
// 实现1, 通过对象来实现
let xiaoMing: Person = {
eat: (food: string, drink: string, fruit?: string) => {
return "123";
},
};
// 实现2, 通过类来实现
class Dog {
eat = (food: string, drink: string, fruit?: string) => {
return "123";
};
}
let coco: Person = new Dog();
console.log(coco.eat("pork", "sprit"));
特别说明:
下面这种匿名的接口里面只能定义一个方法, 如果增加其他字段或者方法, 使用这个接口的对象是永远无法实现这个接口的!!!
interface Eat {
(food: string, drink: string, fruit?: string): string;
}