type和interface的区别

112 阅读1分钟

请参考官方文档

组合方式

interface 使用 extends 来实现继承,type使用&来实现交叉类型。

interface A {
  a:string
}
interface B extends A{
  b: string
}
const c: B ={
  a: 'hi',
  b: 'hi'
}
type AA = {
  aa:string
}
type BB = {
  bb:string
} & AA
const cc: BB ={
  aa: 'hi',
  bb: 'hi'
}

扩展方式

interface可以重复声明用来扩展,type 一个类型只能声明一次。

interface A {
  a:string
}

interface A {
  b:string
}
const a: A ={
  a:'hi',
  b:'hi'
}
type A ={
  a:string
}
// ts报错:Duplicate identifier 'A'.(2300)
type A ={
  b:string
}

范围不同

type适用于基本类型,interface一般不行。

type userName = string
//interface不可以

命名方式

interface会创建一个新的类型名, type只是创建类型别名,并没有新创建类型。

type X = number
const x: X = 1
type Y = typeof x // 此时Y等于number而不是X