Skip to content

Type和Interface

两者都是用来定义类型

  1. interface(接口) 主要用来描述对象、类的结构
    面向对象风格,更像 “契约 / 规范”
    天生支持扩展、继承、合并
    interface User { name: string age: number }

  2. type(类型别名) 给任意类型起别名
    可以是对象、基本类型、联合类型、交叉类型、函数、元组等
    更灵活,功能更全面

    type User = { name: string age: number }

// type 还能干这些,interface 不行 type ID = string | number type Status = "success" | "error" type Fn = (a: number) => string

1、适用范围type全能,interface只能定义类/对象

ts
# type 全能可声明所有数据类型
// 基本类型
type Name = string

// 对象
type Obj = { b: string }; type Obj1 = { a: number }

// 交叉类型
type NewObject = Obj & Obj1

// 联合类型
type Status = "success" | "error"

// 元组
type Data = [number, string]

// 函数
type Fn = (a: number) => void


# interface 只能定义类/对象结构
// ✅ 可以
interface User { name: string }

// ❌ 不行
interface A = string | number

2、拓展方式(interface使用extends而type使用&(交叉类型)
)

ts
#interface 使用 extends

interface Animal { name: string }
interface Cat extends Animal { meow: boolean }

# type 使用 &(交叉类型)
type Animal = { name: string }
type Cat = Animal & { meow: boolean }

3、interface可以合并声明但type不行

ts
interface User {
  name: string
}

interface User {
  age: number
}

// 最终合并为 { name: string; age: number }
const u: User = { name: 'a', age: 18 }

4、type支持映射类型interface不行

ts
type 支持映射类型(interface 不行)
type Readonly<T> = { readonly [K in keyof T]: T[K] }

interface 支持更复杂的索引
interface Dict {
  [key: string]: number
}

type 也能写,但映射类型是 type 独有的强大能力。

5、对类的支持不同

ts
// interface 天生就是为类设计的:

interface A { run(): void }

class Dog implements A {
  run() {}
}
type 也能 implements,但语义上不如 interface 自然。

基于 VitePress 的本地知识库