Scott

type alias vs interface a year ago

typescript
1158个字符
共有110人围观

博客大纲

type大多数情况和interface的功能一样,如都可以表示object

interface有点局限,只能表示object,如果是primitive value还是得靠type alias, 如 type A = string | number | string[]

来看看相同语义在interface和type alias之间的不同表示方法

Tuple

type Address = [number, string]
const address: Address = [1, "BeiJing"]

上面的代码等价于:

interface Address extends Array<number | string> {
    0: number,
    1: string
}
const address: Address = [1, "BeiJing"]

Union

interface Animal {
    name:string;
    age:number;
}

interface Animal {
    sex:string;
}

上面的代码会自动Union(实际开发不建议这么写)等价于:

interface Animal {
    name:string;
    age:number;
    sex:string;
}

使用interface也是有风险的: interface是对外开放的,type则是闭合的

这就意味着如果A文件定义了

interface Animal {
    name:string;
    age:number;
}

如果B文件定义了

interface Animal {
    sex:string;
}

那么就会因为同名interface属性会自动叠加

实际开发中建议interface以I开头命名,如IAnimal

言归正传,用type如何表示Union:

type Animal = {
    name:string;
    age:number;
}

type AnimalB = Animal & {
    sex:string;
}

interface表示:

interface Animal {
    name:string;
    age:number;
}

interface AnimalB extends Animal {
    sex:string;
}