惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
量子位
D
DataBreaches.Net
博客园 - 司徒正美
J
Java Code Geeks
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
aimingoo的专栏
aimingoo的专栏
B
Blog
The Cloudflare Blog
D
Docker
I
InfoQ
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
腾讯CDC
月光博客
月光博客
Hugging Face - Blog
Hugging Face - Blog
Microsoft Azure Blog
Microsoft Azure Blog
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
S
SegmentFault 最新的问题
GbyAI
GbyAI
有赞技术团队
有赞技术团队

博客园 - howhy

TypeScript any vs unknown 详细对比 html 元素包含关系 this 指向 空对象 Object.keys for ...in Reflect.ownKeys ...区别 逻辑运算符和空值运算符 运算符优先级 js 类型显式转换 js 高级函数 js 方法重载 fetch timeout js 任务顺序执行 暂停 js 并发任务 判断两个对象是否相同 js 动态拦截属性 js 通用动画 js groupby js 防抖和节流 实现 instanceof 操作符 js 单例模式 js 数组去重和扁平方法 js 继承方法 js new的过程实现 js deepCopy js '=='的隐性类型转换规则
TypeScript interface vs type 完整对比
howhy · 2026-07-30 · via 博客园 - howhy

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:全能类型别名,支持联合 / 元组 / 基础类型,不可合并