7. TS的interface

TS系列72528 阅读0

标注

interface是对象的模板,可以看作是一种类型约定,中文译为“接口”。使用了某个模板的对象,就拥有了指定的类型结构。也就是说,能用来声明一个对象的结构。

和type类似,但是interface主要用于描述对象结构,不支持直接定义基本类型、联合类型。元组。而type 可以描述任何类型(包括基本类型、联合类型、元组等)。

interface能用extends,可继承多个接口,而type需要用&来组合多个类型。

大多数项目中,interface 用于对象,type 用于组合或复杂类型,是很常见的实践方式。

使用interface :

interface Person {
firstName: string;
lastName: string;
age: number;
}

方括号运算符可以取出 interface 某个属性的类型:

interface Foo {
a: string;
}

type A = Foo['a']; // string

标注对象的方法:

// 写法一
interface A {
f(x: boolean): string;
}

// 写法二
interface B {
f: (x: boolean) => string;
}

// 写法三
interface C {
f: { (x: boolean): string };
}

标注构造函数:(TypeScript 里面,构造函数特指具有constructor属性的类)

interface 内部可以使用new关键字,表示构造函数。

interface ErrorConstructor {
new (message?: string): Error;
}

继承

extends关键字会从继承的接口里面拷贝属性类型,这样就不必书写重复的属性。

如果子接口与父接口存在同名属性,那么子接口的属性会覆盖父接口的属性。注意,子接口与父接口的同名属性必须是类型兼容的,不能有冲突,否则会报错。

interface 还可以继承 type或class定义的对象。

接口合并

多个同名接口会合并成一个接口(不是覆盖)。而type则会报错。

interface Box {
height: number;
width: number;
}

interface Box {
length: number;
}

上面示例中,两个Box接口会合并成一个接口,同时有height、width和length三个属性。同名接口合并时,同一个属性如果有多个类型声明,彼此不能有类型冲突。

同名接口合并时,如果同名方法有不同的类型声明,那么会发生函数重载。而且,后面的定义比前面的定义具有更高的优先级。

评论

发表评论