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

相关推荐
共创splendid--与您携手6 分钟前
AI读取前端项目生成skill.md
前端·人工智能·ai
San813_LDD1 小时前
[C语言]《Dev-C++ 报错解决手册(Day0607 精华版)》
java·前端·javascript
xiaofeichaichai7 小时前
Webpack
前端·webpack·node.js
问心无愧05137 小时前
ctf show web入门111
android·前端·笔记
唐某人丶8 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界8 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌8 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel9 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3119 小时前
https连接传输流程
前端·面试