TypeScript中的这些语句(接口与类型)有什么区别?

interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};

当前回答

在我的日常发展中,当我不知道该选择哪一个时,我会使用这个作弊表。

有关更多信息,请阅读我的博客:https://medium.com/@magenta2127/use-which-interface-or-type-alias-in-typescript-bdfaf2e882ae

其他回答

类型示例:

//为对象创建树结构。由于缺少交集(&),您无法对接口执行相同的操作

type Tree<T> = T & { parent: Tree<T> };

//键入以限制变量仅分配几个值。接口没有联合(|)

type Choise = "A" | "B" | "C";

//由于类型,您可以通过条件机制声明NonNullable类型。

type NonNullable<T> = T extends null | undefined ? never : T;

界面示例:

//您可以使用OOP接口,并使用“implements”定义对象/类骨架

interface IUser {
    user: string;
    password: string;
    login: (user: string, password: string) => boolean;
}

class User implements IUser {
    user = "user1"
    password = "password1"

    login(user: string, password: string) {
        return (user == user && password == password)
    }
}

//可以使用其他接口扩展接口

    interface IMyObject {
        label: string,
    }

    interface IMyObjectWithSize extends IMyObject{
        size?: number
    }

其他答案很棒!Type可以做但Interface不能做的其他事情很少

可以在类型中使用联合

type Name = string | { FullName: string };

const myName = "Jon"; // works fine

const myFullName: Name = {
  FullName: "Jon Doe", //also works fine
};

在类型中迭代联合财产

type Keys = "firstName" | "lastName";

type Name = {
  [key in Keys]: string;
};

const myName: Name = {
  firstName: "jon",
  lastName: "doe",
};

类型中的交集(但是,在带有扩展的接口中也支持)

type Name = {
  firstName: string;
  lastName: string;
};

type Address = {
  city: string;
};

const person: Name & Address = {
  firstName: "jon",
  lastName: "doe",
  city: "scranton",
};

与接口相比,这种类型也不是后来才引入的,根据最新发布的TS类型,它几乎可以做任何接口可以做的事情,而且更多!


*除了声明合并(个人观点:很好,它在类型中不受支持,因为它可能导致代码不一致)

在我的日常发展中,当我不知道该选择哪一个时,我会使用这个作弊表。

有关更多信息,请阅读我的博客:https://medium.com/@magenta2127/use-which-interface-or-type-alias-in-typescript-bdfaf2e882ae

就编译速度而言,组合接口的性能优于类型交集:

[…]接口创建检测属性冲突的单个平面对象类型。这与交叉点类型不同,在交叉点类型中,在对照有效类型进行检查之前,检查每个组成部分。接口之间的类型关系也被缓存,而不是交叉类型。

资料来源:https://github.com/microsoft/TypeScript/wiki/Performance#preferring-交叉口上的接口

TypeScript手册给出了答案:

界面的几乎所有功能都是可用的类型。关键区别在于不能重新打开类型以添加新的财产vs始终可扩展的接口。