接口
接口是由interface
去定义的,知识点分为
- 属性接口
- 函数类型接口
- 可索引接口
- 类类型接口
- 接口扩展
属性接口
每个属性用分号结尾,而不是逗号
1 2 3 4 5 6 7 8 9
| interface UserInfo { name: string; age: number; }
function person(obj: UserInfo) { console.log(obj.name, obj.age); } person({ name: "www", age: 18 });
|
函数类型接口
对函数的参数和返回值进行约束
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
interface UserInfo { (name: string, age: number): string; }
const person: UserInfo = function (name: string, age: number): string { return name + age; }; person("www", 18);
|
可索引接口
对数组和对象进行约束(不常用)
数组例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
interface UserArr { [index: number]: string; }
let arr: UserArr = ["name", "age"];
arr[2] = "sex"
arr["like"] = "yes"
|
对象例子:
当index的类型为string时,代表是对象
1 2 3 4 5 6 7 8 9 10
|
interface UserObj { [index: string]: string; }
let obj: UserObj = {name:"www",age:"18"};
|
类类型接口
对类进行约束,用implements
来获取接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
interface Person { name: string; age(num: number): number; }
class Man implements Person { name: string; constructor(arg_name: string) { this.name = arg_name; } age(num: number) { return num; } }
let man = new Man("www"); console.log(man.age(18))
|
接口扩展
接口是可以用extends
继承的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| interface Things { run(): void; }
interface Doing extends Things { eat(): void; }
class Person implements Doing { name: string; constructor(name: string) { this.name = name; } run() { console.log(this.name + " is running"); }
eat() { console.log(this.name + " is eating"); } }
let person = new Person("www"); console.log(person.run()); console.log(person.eat());
|