boxboxs
技术

type 和 interface的区别

浏览 23最近编辑于
type 和 interface的区别

区别概览 

  • type和interface都可以描述类型,很多场景下他们都可以相互替代,但他们的侧重点不完全一样
  • 实际开发中interface更侧重“描述对象结构和可扩展契约”
  • type偏向“类型表达能力更强的别名工具”

都可以用于定义对象

	interface User {
      name: string
      age: number
    }
    type User2 = {
      name: string
      age: number
    }

type能表示的范围更广

  • 基本类型别名
  • 联合类型
  • 元组
  • 函数类型

type ID = string

type Status = 'success' | 'error' | 'loading'
type Point = [number, number]
tyoe Handler = (e:Event) => void

interface支持类型合并,type不能

interface User {
  name: string
}
interface User {
  age: number
}
// typeScript 会将他们合并成:
interface User {
  name: string
  age: number
}

type不能合并会报错

type User = {
  name: string
}

type User = {
  age: number
} // 报错

都可以扩展,但方式不一样

interface Animal {
  name: string
}

interface Dog extends Animal {
  dark: () => void
}

type通常使用交叉类型

type Animal {
  name: string
}

type Dog = Animal & {
  bark: () => void
}

interface extends更新面向对象里面的继承

type & 更像是类型的组合

两种合并更深的一些差异

extends冲突会立即报错,& 更像是一种尽力而为的操作。所以:extends更强调扩展已有的结构;&更强调同事满足多个条件

interface A {
  id: string
}
interface B extends A { // 报错
  id: number
}

type A = {
  id: string
}
type B = A & {
  id: number
}

它会尝试把属性也做交叉:

id: string & number

而 string & number 基本就是 never。

所以最后常变成:

type B = {
  id: never;
}

这也符合我们的直觉,extends是“继承‘的感觉,你不能和你的继承对象冲突;&更像是”联合“,尽可能的给你”揉“在一起

interface与类实现

interface可以被类实现,语意更加自然

interface Animal {
  name: string
  run(): void
}
class Dog implements Animal {
  name = '旺财'
  run() {
    consolej.log(run)
  }
}

评论 (0)

为了减少垃圾评论,请先使用 GitHub 登录后再发表评论。

使用 GitHub 登录评论

暂无评论,成为第一个评论者!