TypeScript中的interface vs Type
做TS项目,经常会用到interface,和type。一般类型定义我会使用interface,而简单且是约束值的会使用type,比如
type username='bob'|'kelly'
,另外我会通过tslint配置中的Use an interface instead of a type literal.
来进行束缚。BUT,准确的差异在哪,到底该怎么用呢,没法闹,这里调查且总结一番。
官网怎么说
As we mentioned, type aliases can act sort of like interfaces; however, there are some subtle differences.
One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name
Because an ideal property of software is being open to extension, you should always use an interface over a type alias if possible.
On the other hand, if you can’t express some shape with an interface and you need to use a union or tuple type, type aliases are usually the way to go.
官网介绍戳这里