type 和 interface

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; };

  

posted @ 2024-03-13 15:55  monkey-K  阅读(11)  评论(0编辑  收藏  举报