TypeScript2026.08.23 · 1 min read
TypeScript: interface vs type 终极指南
interface 定义是什么,type 描述什么关系。
L
Leo
2026.08.23 · Updated 2026.08.23
1 views
interface 与 type 的分工
interface 定义是什么(对象契约),type 描述什么关系(任意类型组合)。
| interface | type | |
|---|---|---|
| 对象形状 | ✅ 推荐 | ✅ |
| 联合 / 交叉 | ❌ | ✅ |
| 合并声明 | ✅ | ❌ |
示例
type ID = string | number;
interface User {
id: ID;
name: string;
}
function greet(u: User) {
return `你好,${u.name}`;
}
「interface 定义是什么,type 描述什么关系。」一行话写进团队规范。
何时用谁
- 库的公开 API / 可扩展对象 →
interface - 联合、元组、工具类型组合 →
type
TagsTypeScript
L
Leo
BloggerIndependent developer / Blogger and the maintainer of the original blog “大道至简”. Migrating years of posts and shiyu from WordPress to Next.js.
Reader comments
COMMENTS · 0Leave a comment