Interface 接口可以用来定义对象的类型。
功能
- 描述对象的形状(Shape)
- 对类(Class)进行抽象
- Duck Typing(鸭子类型),即如果一个对象有某些属性,那么就可以认为它是某种类型
接口定义
interface Person {
name: string;
age: number;
}
let tom: Person = {
name: 'Tom',
age: 25,
};
倘若不一致:
interface Person {
name: string;
age: number;
}
let tom: Person = {
name: 'Tom',
};
那么会报错:
Type '{ name: string; }' is not assignable to type 'Person'.
Property 'age' is missing in type '{ name: string; }' but required in type 'Person'.
可选属性
当然,也可以定义可选属性:
interface Person {
name: string;
age?: number;
}
let tom: Person = {
name: 'Tom',
};
由于可选属性的存在,那么就不会报错了。
只读属性
interface Person {
readonly id: number;
name: string;
age?: number;
}
let tom: Person = {
id: 89757,
name: 'tom',
age:10,
};
tom.id = 9527;
上述代码会报错:
Cannot assign to 'id' because it is a read-only property.