就让风继续吹吧

贫瘠小行星,种一颗玫瑰

导航

TypeScript 当中 interface 和 type 的区别

1.type 可以用来声明类型别名, interface 不行

type Dog = {
  name: string
  age: number
}

type Cat = {
  breed: string
}

type Animal = Dog | Cat

2.type 可以使用计算属性, interface 不行

type keys = 'dog' | 'cat'
type cubeType = {
  [key in keys]: string
}
const test: cubeType = {
  dog: '',
  cat: '',
}

3.interface 可以合并类型,type 不行

interface Dog {
  name: string
  age: number
}

interface Dog {
  breed: string
}
// 等价于下面这种声明
interface Dog {
  name: string
  age: number
  breed: string
}

 

posted on 2021-04-13 22:44  就让风继续吹吧  阅读(123)  评论(0编辑  收藏  举报