1.约定函数的参数

  1. function eat(food: string) {
  2. return `${food} is very delicious!`;
  3. }

2.约定函数的参数和返回值

  1. function eat(food: string): string {
  2. return `${food} is very delicious!`;
  3. }

3.函数返回多个值(元祖)

  1. function walk(distance: string): [string, number] {
  2. return [`${distance} is very far!`, 1];
  3. }

4.函数类型的接口

  1. interface Person {
  2. eat: Eat; // 接口嵌套定义
  3. walk?(a: number): boolean; // 直接定义
  4. }
  5. interface Eat {
  6. (food: string, drink: string, fruit?: string): string;
  7. }
  8. // 函数类型接口的实现
  9. // 实现1, 通过对象来实现
  10. let xiaoMing: Person = {
  11. eat: (food: string, drink: string, fruit?: string) => {
  12. return "123";
  13. },
  14. };
  15. // 实现2, 通过类来实现
  16. class Dog {
  17. eat = (food: string, drink: string, fruit?: string) => {
  18. return "123";
  19. };
  20. }
  21. let coco: Person = new Dog();
  22. console.log(coco.eat("pork", "sprit"));

特别说明:

下面这种匿名的接口里面只能定义一个方法, 如果增加其他字段或者方法, 使用这个接口的对象是永远无法实现这个接口的!!!

  1. interface Eat {
  2. (food: string, drink: string, fruit?: string): string;
  3. }