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

相关推荐
Surmon42 分钟前
基于 Cloudflare 生态的 AI Agent 实现
前端·人工智能·架构
六月June June5 小时前
自定义调色盘组件
前端·javascript·调色盘
SY_FC6 小时前
实现一个父组件引入了子组件,跳转到其他页面,其他页面返回回来重新加载子组件函数
java·前端·javascript
糟糕好吃6 小时前
我让 AI 操作网页之后,开始不想点按钮了
前端·javascript·后端
陈天伟教授6 小时前
人工智能应用- 天文学家的助手:08. 星系定位与分类
前端·javascript·数据库·人工智能·机器学习
VaJoy6 小时前
给到夯!前端工具链新标杆 Vite Plus 初探
前端·vite
小彭努力中8 小时前
191.Vue3 + OpenLayers 实战:可控化版权信息(Attribution)详解与完整示例
前端·javascript·vue.js·#地图开发·#cesium
奇舞精选8 小时前
用去年 github 最火的 n8n 快速实现自动化推送工具
前端·agent
奇舞精选8 小时前
实践:如何为智能体推理引入外部决策步骤
前端·agent
无限大68 小时前
AI实战02:一个万能提示词模板,搞定90%的文案/设计/分析需求
前端·后端