如果你简历上的技能包括写TypeScript,面试官可能会问你type和interface有什么区别?你知道如何回答这个问题吗?如果你不知道,也许看完这篇文章你就会明白了。类型别名type可用于为类型赋予新名称,这在命名非对象类型(如基本类型或联合类型)时很有用:typeMyNumber=number;typeStringOrNumber=string|数字;类型文本=字符串|细绳[];输入Point=[number,number];类型回调=(数据:字符串)=>无效;在TypeScript1.6中,类型别名支持泛型。我们工作中常用的工具类型,如Partial、Required、Pick、Record、Exclude,都是以类型的形式定义的。//lib.es5.d.tstypePartial={[PinkeyofT]?:T[P];};typeRequired={[PinkeyofT]-?:T[P];};typePick={[PinK]:T[P];};typeRecord={[PinK]:T;};类型Exclude=TextendsU?从不:T;而interface接口只能用来定义对象类型,Vue3中的App对象是使用接口定义的://packages/runtime-core/src/apiCreateApp.tsexportinterfaceApp{version:string配置:AppConfig使用(插件:插件,...选项:任何[]):这个mixin(mixin:ComponentOptions):这个组件(名称:字符串):组件|undefined//Gettercomponent(name:string,component:Component):this//Setterdirective(name:string):Directive|undefineddirective(name:string,directive:Directive):this}从上面的代码可以看出,在定义使用接口的时候,我们可以在一个对象类型上同时声明属性和方法。了解了类型和接口的作用之后,我们先介绍一下它们的相同点。1.类型别名和接口都可以用来描述对象或函数。类型别名typePoint={x:number;y:数字;};输入SetPoint=(x:number,y:number)=>void;在上面的代码中,我们使用type关键字为对象字面量类型和函数类型分别取了一个别名,这样就可以在其他地方使用这些类型。界面界面点{x:数字;y:number;}interfaceSetPoint{(x:number,y:number):void;}2.类型别名和接口都支持扩展。类型别名用&(交集运算符)扩展,而接口用extends扩展。type别名扩展typeAnimal={name:string}typeBear=Animal&{honey:boolean}constbear:Bear=getBear()bear.namebear.honeyinterfaceextensioninterfaceAnimal{name:string}interfaceBearextendsAnimal{honey:boolean}另外,接口也可以通过extends扩展类型别名定义的类型:operator)Definedinterfacetype:interfaceAnimal{name:string}typeBear=Animal&{honey:boolean}明白了类型和接口的相同点之后,我们来介绍一下它们的不同点。1.类型别名可以为基本类型、联合类型或元组类型定义别名,但接口不能。输入MyNumber=数字;输入StringOrNumber=字符串|数字;类型点=[数字,数字];2。具有相同名称的接口将自动合并,但类型别名不会。同名接口合并interfaceUser{name:string;}interfaceUser{id:number;}letuser:User={id:666,name:"Abaoge"};user.id;//666用户名;//类型别名与“阿宝哥”同名会冲突typeUser={name:string;};//标识符“User”重复。ts(2300)typeUser={//错误id:number;};利用自动合并同名接口的特性,我们可以在开发第三方库时为用户提供更好的安全性。例如webext-bridge库使用interface定义了ProtocolMap接口,用户可以自由扩展ProtocolMap接口。后面在使用库提供的onMessage函数监听自定义消息时,可以推断出不同消息对应的消息体类型。ExtendProtocolMapinterfaceimport{ProtocolWithReturn}from'webext-bridge'declaremodule'webext-bridge'{exportinterfaceProtocolMap{foo:{title:string}bar:ProtocolWithReturn}}监听自定义消息import{onMessage}from'webext-bridge'onMessage('foo',({data})=>{//`data`的类型将是`{title:string}`console.log(data.title)}使用类型别名的场景:定义基本类型的别名时使用type定义元组类型时使用type定义函数类型时使用type定义联合类型时使用type定义映射类型时使用type的场景usinginterfaces:必需当使用接口的自动合并特性时,使用接口。在不使用类型的情况下定义对象类型时使用接口。