TypeScript-接口

属性接口

1
2
3
4
5
6
7
8
9
10
11
12
interface PersonInfo {
firstName: string;
secondName?: string;// 可选属性
}

function printName(info: PersonInfo) {
console.log(info.firstName + info.secondName);
}

printName({
firstName: 'zhang',
});

函数类型接口

1
2
3
4
5
6
7
interface encrypt {
(key: string, value: string): string;
}

let md5: encrypt = function (key: string, value: string): string {
return key + value;
};

可索引接口

对数组约束

1
2
3
4
5
interface UserArr {
[index: number]: string;
}

let arr1: UserArr = ['aaa'];

对对象约束

1
2
3
4
5
interface UserObj {
[index: string]: string;
}

let obj: UserObj = {name: 'aaa'};

类类型接口

与抽象类类似

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface UserAnimal {
name: string;

eat(str: string): void;
}

class UserDog implements UserAnimal {
name: string;

constructor(name: string) {
this.name = name;
}

// 参数可选
eat(): void {
console.log(this.name);
}
}

接口的扩展

可继承

1
2
3
4
5
6
7
interface food {
eat(): void;
}

interface Banana extends food {
work(): void;
}
0%