同样是定义对象,为什么 TS 里有人用 interface,有人用 type?

js 复制代码
interface User {  
id: number  
name: string  
email: string  
role: string  
status: 'active' | 'inactive'  
createdAt: string  
} 
js 复制代码
type CreateUserData = Pick<User, 'name' | 'email' | 'role'>

同样都是定义对象,为什么User 使用interface定义,而CreateUserData 使用type定义

这是 TypeScript 的一个经典问题。两者定义普通对象时几乎等价,区别在于能力范围

js 复制代码
// ✅ type 可以接受任何类型表达式的结果
type CreateUserData = Pick<User, 'name' | 'email' | 'role'>
type A = User | Admin         // 联合类型
type B = string | number      // 基础类型联合
type C = User & { extra: string }  // 交叉类型

// ❌ interface 只能描述对象结构,不能直接等于一个"计算结果"
interface CreateUserData = Pick<User, 'name' | 'email' | 'role'>  // 语法错误!

Userinterface 是一种习惯约定,用 type 也完全合法
两者的实际差异(记住这两点就够了):

js 复制代码
// 1. interface 可以"声明合并"(同名自动合并),type 不行
interface User { id: number }
interface User { name: string }
// 结果:User = { id: number; name: string }  ← 自动合并

type User = { id: number }
type User = { name: string }  // ❌ 报错:重复标识符

// 2. type 可以描述任意类型,interface 只能描述对象,同时不能直接等于一个"计算结果"
type ID = string | number         // ✅ type 可以
interface ID = string | number    // ❌ interface 不行

简单记忆:能用 interface 就用 interfaceinterface 做不到的用 type

相关推荐
Wect3 分钟前
TypeScript 完全指南
前端·javascript·typescript
hunterandroid6 分钟前
Fragment 事务与状态丢失:从崩溃现场到稳定治理
前端
清风programmer6 分钟前
H5与小程序通信
前端·vue.js·uni-app
张元清7 分钟前
React useDeepCompareEffect:修复 useEffect 的对象依赖问题(2026)
javascript·react.js
不一样的少年_14 分钟前
原来 AI Agent 的核心循环这么简单:手搓一个 Agent Loop
前端·后端·agent
爱勇宝38 分钟前
你以为自己性格不好,其实只是被环境反复训练
前端·后端·程序员
phltxy41 分钟前
LangChain_v1_Agent快速开发和更新说明
前端·javascript·langchain
Cobyte41 分钟前
通过 Vite 运行手写的模板编译器
前端·javascript·vue.js
Hyyy41 分钟前
Agent 工作流
前端
Bigger42 分钟前
🔥每天最难的问题不是做饭,而是今天到底吃什么——我做了「烟火食间」
前端·人工智能·agent