本文深入解析TypeScript中type与interface的区别。两者均可定义对象或函数形状,但type支持基本类型别名、联合类型、元组及交叉类型,而interface具备声明合并特性。官方建议优先使用interface,因其能更好地检测属性冲突且性能更优,仅在需要组合类型时使用type。
前言
在TypeScript开发中,type和interface是两个极易混淆的概念。尽管它们都用于定义接口或类型结构,但在实际应用场景中存在显著差异。本文将详细阐述这两者的联系与区别,帮助开发者彻底厘清其用法。
type和interface的相同点
从本质上看,它们都是定义对象或函数形状的手段,目的相同。具体示例如下:
interface example {
name: string
age: number
}
interface exampleFunc {
(name:string,age:number): void
}
type example = {
name: string
age: number
}
type example = (name:string,age:number) => void两者均支持继承机制,且并非相互独立,而是可以互相继承,只是语法形式略有不同。
type exampleType1 = {
name: string
}
interface exampleInterface1 {
name: string
}
type exampleType2 = exampleType1 & {
age: number
}
type exampleType2 = exampleInterface1 & {
age: number
}
interface exampleInterface2 extends exampleType1 {
age: number
}
interface exampleInterface2 extends exampleInterface1 {
age: number
}对于interface,继承通过extends关键字实现;而对于type,则通过&符号实现,这被称为交叉类型(Intersection Types)。
type和interface的不同点
首先分析type具备但interface无法实现的功能。
- type可以定义基本类型的别名,例如:
type myString = string - type可以利用typeof操作符基于现有值或类型进行定义,例如:
type myType = typeof someObj - type可以声明联合类型(Union Types),例如:
type unionType = myType1 | myType2 - type可以定义元组类型(Tuple Types),例如:
type yuanzu = [myType1, myType2]
接下来分析interface具备但type无法实现的功能。
interface支持声明合并(Declaration Merging),示例如下:
interface test { name: string } interface test { age: number } /* test实际为 { name: string age: number } */若使用type定义同名标识符,后者的定义将覆盖前者,始终只有最后一个type生效,无法实现合并。
结语
TypeScript中还存在许多易混淆的概念,如extends与implements的区别,以及泛型等高级特性。这些都是掌握TypeScript必须深入理解的知识点。
TypeScript在提升代码健壮性的同时,也引入了更多概念。因此需要持续学习。未来将输出更多关于TypeScript的文章,以加深理解并帮助读者。
如何选择 Interface 、 Type
尽管官方文档指出几乎接口的所有特性都可以通过类型别名实现,但官方建议优先选择interface,仅在接口无法满足需求时使用类型别名。TypeScript官网在“Preferring Interfaces Over Interps”章节中有明确说明,具体内容如下:
在大多数情况下,简单的对象类型别名与接口的作用非常相似。
interface Foo { prop: string }
type Bar = { prop: string };
然而,当需要组合两个或多个类型来构建新类型时,可以选择使用接口扩展这些类型,或者使用类型别名将它们交叉合并,此时差异开始显现。
- 接口会创建一个单一的平面对象类型来检测属性冲突,这通常至关重要。而交叉类型仅递归地进行属性合并,在某些情况下可能导致生成never类型。
- 接口的显示效果通常更直观,而交叉类型作为其他交叉类型的一部分时,直观表现不佳,容易被误认为是不同基本类型的简单组合。
- 接口之间的类型关系会被缓存,而交叉类型被视为组合后的一个整体。
- 另一个值得注意的区别是,在检查目标类型之前,会先检查每一个组分。
基于上述原因,官方建议使用接口或扩展来构建类型,而不是创建交叉类型。
- type Foo = Bar & Baz & {
- someProp: string;
- }
+ interface Foo extends Bar, Baz {
+ someProp: string;
+ }
简而言之,接口更符合JavaScript对象的工作方式。当出现属性冲突时:
// 接口扩展
interface Sister {
sex: number;
}
interface SisterAn extends Sister {
sex: string;
}
// index.ts(5,11): error TS2430: Interface 'SisterAn' incorrectly extends interface 'Sister'.
// Types of property 'sex' are incompatible.
// Type 'string' is not assignable to type 'number'.
// 交叉类型
type Sister1 = {
sex: number;
}
type Sister2 = {
sex: string;
}
type SisterAn = Sister1 & Sister2;
// 不报错,此时的 SisterAn 是一个'number & string'类型,也就是 never
总结
本文介绍了TypeScript中type与interface的区别。更多相关类型定义内容请搜索本站历史文章或继续浏览后续文章,希望大家多多支持。