TypeScript 中的这些语句(interface 与 type)有什么区别?
What is the difference between these statements (interface vs type) in TypeScript?
interface X { a: number b: string } type X = { a: number b: string }; 推荐答案2021 年 3 月更新:较新的 TypeScript 手册有一个部分 接口与类型别名,解释了这些差异.
Update March 2021: The newer TypeScript Handbook has a section Interfaces vs. Type Aliases which explains the differences.
原始答案 (2016)
根据 (现已存档)TypeScript 语言规范:
与总是引入命名对象类型的接口声明不同,类型别名声明可以为任何类型的类型引入名称,包括原始类型、联合类型和交集类型.
Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.
规范继续提到:
接口类型与对象类型的类型别名有很多相似之处文字,但由于接口类型提供了更多的功能,它们是通常首选键入别名.例如接口类型
Interface types have many similarities to type aliases for object type literals, but since interface types offer more capabilities they are generally preferred to type aliases. For example, the interface type interface Point { x: number; y: number; }
可以写成类型别名
type Point = { x: number; y: number; };然而,这样做意味着失去以下功能:
However, doing so means the following capabilities are lost:
- 可以在 extends 或 implements 子句中命名接口,但对象类型文字的类型别名不能自 TS 2.7 起不再适用.
- 一个接口可以有多个合并声明,但有一个类型别名对于对象类型文字不能.
- An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot No longer true since TS 2.7.
- An interface can have multiple merged declarations, but a type alias for an object type literal cannot.
更多推荐
TypeScript 中的接口与类型
发布评论