Type or interface: typescript 到底用哪个
Type 和Interface*都是用于描述TypeScript中对象的结构。
TypeScript分为三种类中,Any Type,Build-In Type,User-Defined Type。
Type 与 Interface 相同点
定义TypeScript中User-Defined Type,为函数或对象的定义契约。
1 | interface people { |
两者可以相互继承。interface通过extends实现继承,type通过&实现。
1 | interface people { |
不同点
type可以定义基本类型的别名type myNumber = number;可以通过typeof定义,type myT = typeof myObj;可以申明联合类型和元组类型,type myT = exampleType1 | exampleType2; type myT = [exampleType1, exampleType2]type不能重复定义,无法声明合并,interface可以。
1 | interface people { |
参考
What is the difference between interface and type in TypeScript ?