Typescript 中的 interface 和 type 到底有什么区别详解
interfaceVStype
大家使用typescript总会使用到interface和type,官方规范稍微说了下两者的区别
- Aninterfacecanbenamedinanextendsorimplementsclause,butatypealiasforanobjecttypeliteralcannot.
- Aninterfacecanhavemultiplemergeddeclarations,butatypealiasforanobjecttypeliteralcannot.
但是没有太具体的例子。
明人不说暗话,直接上区别。
相同点
都可以描述一个对象或者函数
interface
interfaceUser{ name:string age:number } interfaceSetUser{ (name:string,age:number):void; }
type
typeUser={ name:string age:number }; typeSetUser=(name:string,age:number):void;
都允许拓展(extends)
interface和type都可以拓展,并且两者并不是相互独立的,也就是说interface可以extendstype,type也可以extendsinterface。虽然效果差不多,但是两者语法不同。
interfaceextendsinterface
interfaceName{ name:string; } interfaceUserextendsName{ age:number; }
typeextendstype
typeName={ name:string; } typeUser=Name&{age:number};
interfaceextendstype
typeName={ name:string; } interfaceUserextendsName{ age:number; }
typeextendsinterface
interfaceName{ name:string; } typeUser=Name&{ age:number; }
不同点
type可以而interface不行
type可以声明基本类型别名,联合类型,元组等类型
//基本类型别名 typeName=string //联合类型 interfaceDog{ wong(); } interfaceCat{ miao(); } typePet=Dog|Cat //具体定义数组每个位置的类型 typePetList=[Dog,Pet]
type语句中还可以使用typeof获取实例的类型进行赋值
//当你想获取一个变量的类型时,使用typeof letdiv=document.createElement('div'); typeB=typeofdiv
其他骚操作
typeStringOrNumber=string|number; typeText=string|{text:string}; typeNameLookup=Dictionary; typeCallback =(data:T)=>void; typePair =[T,T]; typeCoordinates=Pair ; typeTree =T|{left:Tree ,right:Tree };
interface可以而type不行
interface能够声明合并
interfaceUser{ name:string age:number } interfaceUser{ sex:string } /* User接口为{ name:string age:number sex:string } */
总结
一般来说,如果不清楚什么时候用interface/type,能用interface实现,就用interface,如果不能就用type。其他更多详情参看官方规范文档
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。