# 接口
ts 里的接口可以规范对象和类的类型.
# 基本用法
interface IPerson { name: string; age: number; } const man: IPerson = { name: "wanmao", age: 18 };
Copied!
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
对象的属性必须与接口里规定的属性一致, 不能改名, 不能增加, 也不能漏写.
# 可选属性
我们可以使用可选属性, 让接口更灵活:
interface IAnimal { name: string; age?: number; } const animal: IAnimal = { name: "猪猪" };
Copied!
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
这仅仅意味着number
属性是可加可不加的, 其他的操作仍然是失败的.
# 任意属性
有时候我们希望一个接口允许有任意的属性, 可以使用如下方式:
interface IPhones { name: string; G: number; [prop: string]: any; } let phone: IPhones = { name: "hua-wei", G: 5, days: 251 };
Copied!
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
需要注意的是:一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集.
# 只读属性
有时候我们希望对象中的一些字段只能在创建的时候被赋值,那么可以用 readonly
定义只读属性:
interface IFruit { readonly color: string; } const fruit: IFruit = { color: "red" };
Copied!
1
2
3
4
5
6
7
2
3
4
5
6
7
← 原始数据类型 & 联合类型 数组 →