什么是接口
在面向对象语言中,接口(Interfaces)是一个很重要的概念,它是对行为的抽象,而具体如何行动需要由类(classes)去实现(implement)。
TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。
我对接口的理解
interface 像是在编程人员可以自定义一些数据类型,typescript就是严格就完事,所谓的严格就是针对类型来说的,你想增加,或者想减少都是不可以的。
demo:
interface Person {
age: number;
name: string;
}
// 少写一个会报错
let kate: Person = {
age: 888
// 报错: 'name' is declared here. 接口声明了name
}
// 多写也会报错
let kate: Person = {
age: 888,
name: 'kate',
weight: 452
// 报错: ype '{ age: number; name: string; weight: number; }' is not assignable to type 'Person'.
//Object literal may only specify known properties, and 'weight' does not exist in type 'Person'.
}
// 正确的:
let kate: Person = {
age: 888,
name: '王吉祥'
}
可选属性
可选属性,允许有这个属性,或者没有这个属性,但是不能够多添加属性,多添加还是会报错。
interface Person {
age: number;
name?: string;
}
// 正确
let kate: Person = {
age: 888,
name: 'kate'
}
// 正确
let kateOther: Person = {
age: 888,
}
任意属性
有时候我们需要,允许有任意的属性;既然是任意属性,那必然是属性key要规定类型,value值应该是任意的。
当有了任意属性,那么确定属性和可选属性类型 都必须是它的子类型
将这个任意属性的类型确定用联合类型来定义,也是一个很不错的选择
interface Box {
height: number;
color: string;
[propName: string]: number | string;
}
// 也可以这么定义接口
interface Box {
height: number;
color: string;
[propName: string]: any;
}
// 正确的
let box1: Box = {
height: 888,
color: '#f60',
weight: '999'
}
只读属性 readonly
有时候我们希望对象中的一些字段只能在被创建的时候赋值,其余时候是不能进行赋值操作的,只能使用,例如一些协议返回的id,是可以读,但是你不可以去修改。
interface Flow {
color: string;
num: number;
readonly type: string;
}
let meigui: Flow = {
color: 'red',
num: 999,
type: 'meigui'
}
meigui.color = 'yellow'; // 正确,没问题,不回去报错
meigui.type = 'guihua'; // 会报错,Cannot assign to 'type' because it is a read-only property.
注意,只读的约束存在于第一次给对象赋值的时候,而不是第一次给只读属性赋值的时候
interface Flow {
color: string;
num: number;
readonly type: string;
}
let meigui: Flow = {
color: 'red',
num: 999,
}
meigui.type = 'guihua'
// 相关报错解析
//Found 2 errors. Watching for file changes.
// 1、Property 'type' is missing in type '{ color: string; num: number; }' but required in type 'Flow'. 创建Flow对象的时候没有给type赋值
// 2、 Cannot assign to 'type' because it is a read-only property.