范围不同
范围不同:type适用于基本类型,interface一般不行。
type A = 'AAA'
interface B 'BBB' // ❌不能这样写
扩展方式
interface可以 重复 声明用来扩展,type一个类型只能声明 一次
interface A {
name: string
}
interface A {
age: number
}
const a: A = {
name: 'jack',
age: 22
}
type b = {// ❌报错
name: string
}
type b = {// ❌报错
age: number
}
命名方式:
interface会创建新的类型名,type只是创建类型别名,并没有新创建 类型。
鼠标移上去看到的提示不一样
type Man = {
name: string
}
const jack:Man = {name: 'jack'}
type J = typeof jack // 鼠标移上去看到的是 {name: 'jack'}
interface Cat {
name: string
}
const cat:Cat = {name: 'tom'}
type C = typeof cat // 鼠标移上去看到的是 Cat
组合方式
interface使用extends来实现继承,type使用&来实现联合类型。
interface A {
a: string
}
interface B extends A {
b: number
}
type C = {
c: boolean
}
type D = {
d: null
} & C
const bb: B = {
a: 'aaa',
b: 23
}
const dd: D = {
c: true,
d: null
}