type 和 interface 的区别:

  1. 相同点:
    1. 都能定义对象类型
  2. 不同点:
      1. type能表示非对象类型(值类型),interface 只能表示对象类型(数组,函数,对象)
      2. interface 可以 extends, type 不可以,type 使用 & 合并类型;(type 可以 & interface;interface 可以 extends type)
      3. interface 可以重名定义,自动合并;type 不能重名
      4. interface 可以使用 this,type不可以
        1. interface Foo { add(num: number): this; }
      5. type 可以扩展原始数据类型,interface 不行
        1. // 正确 type MyStr = string & { type: “new”; }; // 报错 interface MyStr extends string { type: “new”; }
      6. interface 不能包含属性映射(mapping),type 可以;
        1. interface Point { x: number; y: number; // 正确 type PointCopy1 = { [Key in keyof Point]: Point[Key]; }; // 报错 interface PointCopy2 { [Key in keyof Point]: Point[Key]; };
      7. interface 无法表达某些复杂类型(交叉类型和联合类型),type 可以;(无法表达 A 或 B,A 且 B)
        1.   type A = { /* … */ }; type B = { /* … */ }; type AorB = A | B; type AorBwithName = AorB & { name: string; };

  

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。