同样是定义对象,为什么 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

相关推荐
古夕8 分钟前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js
朦胧之11 分钟前
页面白屏卡住排查方法
前端·javascript
用户5936087414012 分钟前
Playwright 黑魔法:用 ClipboardEvent 绕过 React 富文本编辑器
前端
Ruihong15 分钟前
Vue withDefaults 转 React:VuReact 怎么处理?
vue.js·react.js·面试
石山岭42 分钟前
自己动手写了一个 Android 虚拟定位 App:GPSSimulate 技术实
android·前端
犇驫聊AI1 小时前
Chrome DevTools MCP + Claude Code 自定义skills生成接口代码生成器
前端·javascript
kyriewen1 小时前
别再这样写 async/await 了:我在 Code Review 中见过最多的 8 个错误
前端·javascript·面试
hoLzwEge1 小时前
node-linker VS shamefully-hoist
前端·前端框架
袋鱼不重2 小时前
解决 Web 端图片预览与下载颜色不一致的一种工程方案
前端·后端
风止何安啊2 小时前
教你用 JS + AI 实现简单的爬虫,零门槛爬取网页信息
前端