Skip to content

typescript 中 type 和 interface 的区别 #16

Open
@myLightLin

Description

@myLightLin

区别

  1. 它们都可以用来描述对象的形状
type Point = {
  x: number;
  y: number;
}
interface Point {
  x: number;
  y: number;
}
  1. interface 会进行声明合并,而 type 不行
interface Point {
  x: number;
  y: number;
}

interface Point {
  z: number;
}
type Point = {
  x: number;
  y: number;
}

type Point = {
  z: number;
}
// 编译失败,报错 oops
  1. type 可以定义 primitive type、tuple 、function type 、 union type 等类型;而 interface 则用于定义 object types
  2. type 通过 & 来合并多个属性,而 interface 通过 extends 来继承属性

使用场景

  • 如果 type 和 interface 都可以,优先使用 interface 定义
  • 如果是一些大型项目,使用 interface 定义 API,方便继承
  • 组件的 props 属性使用 type 定义

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions