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
}
原文地址:https://www.cnblogs.com/jiawei-Wang/p/14655751.html