一般我选择的是,和对象相关的,使用interface,和对象不相关的使用type
- 组合方式:interface 使用 extends 来实现继承,type 使用 & 来实现交叉类型。
insterface B {
b: string
}
insterface A extends B {
a: string
}
const a: A = {
a: 'hi',
b: 'hi'
}
=================================================================
type BB = {
bb: string
}
type AA = {
aa: string
} & BB
const aa: AA = {
aa: 'hi',
bb: 'hi'
}
- 扩展方式:interface 可以重复声明用来扩展,type 一个类型只能声明一次
insterface A {
a: string
}
insterface A {
b: string
}
const a: A = {
a: 'hi',
b: 'hi'
}
=========================================================
type A = {
a: string
}
type A = {
b: string
}
有点像 const
- 范围不同:type 适用于基本类型,interface 一般不行。
type UserName:string = 'zs'
insterface 无法实现UserName是一个string类型
- 命名方式:interface 会创建新的类型名,type 只是创建类型别名,并没有新创建类型。