type 和 interface
type 和 interface 的区别:
- 相同点:
- 都能定义对象类型
- 不同点:
- type能表示非对象类型(值类型),interface 只能表示对象类型(数组,函数,对象)
- interface 可以 extends, type 不可以,type 使用 & 合并类型;(type 可以 & interface;interface 可以 extends type)
- interface 可以重名定义,自动合并;type 不能重名
- interface 可以使用 this,type不可以
- interface Foo { add(num: number): this; }
- type 可以扩展原始数据类型,interface 不行
- // 正确 type MyStr = string & { type: "new"; }; // 报错 interface MyStr extends string { type: "new"; }
- interface 不能包含属性映射(mapping),type 可以;
- interface Point { x: number; y: number; } // 正确 type PointCopy1 = { [Key in keyof Point]: Point[Key]; }; // 报错 interface PointCopy2 { [Key in keyof Point]: Point[Key]; };
- interface 无法表达某些复杂类型(交叉类型和联合类型),type 可以;(无法表达 A 或 B,A 且 B)
- type A = { /* ... */ }; type B = { /* ... */ }; type AorB = A | B; type AorBwithName = AorB & { name: string; };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)