admin 管理员组

文章数量: 887007

ts接口定义

1.属性接口

  • 对自定义方法中传入参数的约束
interface FullName {firstName: string;secondName: string;age?: number;
}function printName(name: FullName) {console.log(name.firstName + '--' + name.secondName);
}const obj = {firstName: '张',secondName: '三'
}
printName(obj);

2.函数类型接口

  • 对方法传入的参数以及返回值进行约束
interface encrypt {(key: string, value: string): string;
}var md5: encrypt = function(key: string, value: string) {return key + value;
}console.log(md5('张', '三'));

3.可索引接口

  • 对数组和对象的约束
// 数组的约束
interface UserArr {// [索引]:值[index: number]: string;
}
const arr: UserArr = ['111', '222'];// 对象的约束
interface UserObj {[index: string]: number;
}
const obj: UserObj = {name: 123,age: 321
}

4.类类型接口

  • 对类的约束(类似于抽象类)
interface Animal {name: string;eat(str: string): void;
}
// implements 实现接口
class Dog implements Animal {name: string;constructor(name: string) {this.name = name;}eat() {console.log(this.name + '吃狗粮');}
}const d = new Dog('小黑');
d.eat();

5.接口扩展

  • 接口可以继承接口
interface Animal {name: string;eat(str: string): void;
}interface Person extends Animal {work(): void;
}class Programer {name: string;constructor(name: string) {this.name = name;}coding() {console.log(this.name + '在写代码');}
}class Web extends Programer implements Person {constructor(name: string) {super(name);}work(): void {console.log(this.name + '在工作中');}eat(): void {console.log(this.name + '在吃饭');}
}const p = new Web('张三');
p.work();
p.eat();
p.coding();

本文标签: ts接口定义