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 @   monkey-K  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示