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

相关推荐
誰在花里胡哨10 小时前
Vue<前端页面装修组件>
前端·vue.js
张元清10 小时前
Pareto 动态路由实战:[slug]、catch-all、嵌套布局
前端·javascript·面试
fix一个write十个10 小时前
NativeWind v4 与 React Native UI Kit或三方库样式隔离指南
前端·react native
懂懂tty10 小时前
React中BeginWork和CompleteWork解析
前端·react.js
_下雨天.11 小时前
HAProxy搭建Web群集
前端
梦想CAD控件11 小时前
在线CAD开发包图纸转换功能使用指南
前端·javascript·vue.js
亚空间仓鼠11 小时前
Ansible之Playbook(三):变量应用
java·前端·ansible
invicinble11 小时前
前端技术栈整理
前端
倾颜11 小时前
pnpm monorepo 下,如何把 Next.js 应用里的稳定内核拆成内部 workspace 包
前端·react.js·next.js
念格11 小时前
Flutter 仿微信输入框最佳实践:自适应高度 + 超行数智能切换全屏
前端·flutter