TypeScript interface vs type 完整对比

1. 基础定义

interface 接口

专门描述对象结构、类、函数、数组,支持合并声明,面向对象风格。
interface User {
  id: number
  name: string
}

type 类型别名

给任意类型起别名(对象、联合、交叉、基础类型、元组),不能重复声明合并。
type User = {
  id: number
  name: string
}

2. 核心区别(重点)

① 重复定义:interface 自动合并,type 直接报错

// interface 重复声明会合并
interface User { name: string }
interface User { age: number }
const u: User = { name: "张三", age: 18 }; // 合法

// type 重复定义直接报错,不允许
type User = { name: string }
type User = { age: number } // 报错:标识符重复

② 扩展方式

interface 使用 extends 继承

interface User { name: string }
interface Admin extends User { role: string }

type 使用交叉类型 &

type User = { name: string }
type Admin = User & { role: string }

③ 支持类型范围(type 更强)

type 可以定义:基础类型、联合、交叉、元组、函数、任意组合
// 基础类型别名
type Str = string;
// 联合类型(interface 做不到)
type Status = "success" | "fail" | "loading";
// 元组
type Point = [number, number];
// 函数
type Fn = (a: number) => string;
 
interface 只能描述对象 / 类结构,不能定义联合、基础类型。

④ 类实现 implements 两者都支持

interface IUser { name: string }
type TUser = { name: string }

class A implements IUser { name = "a" }
class B implements TUser { name = "b" }

⑤ 函数 / 数组写法差异

  1. interface 函数
interface Fn {
  (x: number): void
}
  1. type 函数(更直观)
type Fn = (x: number) => void

3. 相同点

  1. 都可以描述对象结构,支持可选属性、只读属性
interface User {
  readonly id: number;
  nick?: string;
}
type User = {
  readonly id: number;
  nick?: string;
}
  1. 都能被泛型约束
interface I<T> { data: T }
type T<T> = { data: T }
  1. 都可以使用 ? 可选、readonly 只读修饰符

4. 开发使用规范(业界通用)

优先用 interface

  1. 描述对象、后端实体、类结构
  2. 需要多处扩展、需要声明合并(插件、扩展全局类型)
  3. 给类 implements 实现

优先用 type

  1. 需要联合 / 交叉类型(| / &
  2. 基础类型、元组、函数类型简写
  3. 复杂复合类型、一次性不会扩展的简单对象

5. 示例对比

场景 1:对象实体 → interface

interface Account {
  id: number
  username: string
}
interface AdminAccount extends Account {
  permission: string[]
}

场景 2:状态联合 → type

type PageState = "idle" | "loading" | "done" | "error";

场景 3:函数类型 → type

type Handler = (val: string) => Promise<void>;

总结一句话

  • interface:对象专用,支持合并、extends 继承
  • type:全能类型别名,支持联合 / 元组 / 基础类型,不可合并
posted @ 2026-07-30 17:10  howhy  阅读(12)  评论(0)    收藏  举报