跳转至

G2-5 type vs interface 统计报告

目的:完整统计 src/typeinterface 的使用频率 方法grep -rE "^(export )?type [A-Z]|^(export )?interface [A-Z]" 执行日期:2026-06-06


1. 总览

维度 数量 占比
type 定义 2,477 97%
interface 定义 85 3%
总类型定义 2,562 100%

type 压倒性主导——97% vs 3%


2. type 的细分

type 形式 数量
type X = Y(基本别名) 1,271(51%) type Status = 'pending' \| 'done'
type X<Y> = ...(泛型别名) 45 type Container<T> = { items: T[] }
type X = A \| B(联合) 18 type Mode = 'normal' \| 'vim'
type X = { ... }(对象字面量) 5 type X = { a: string }
其他(函数 / 工具类型 / 递归等) 1,138 各种

3. interface 的特征

3.1 85 个 interface 集中在哪里

文件 interface 数 备注
utils/analyzeContext.ts 12 上下文分析(最多)
types/generated/.../claude_code_internal_event.ts 5 生成代码(protobuf/buf)
utils/imageResizer.ts 4 图片处理
components/permissions/FilePermissionDialog/ideDiffConfig.ts 4 IDE diff 配置
services/mcp/types.ts 3 MCP 类型
components/StructuredDiff/Fallback.tsx 3 diff fallback
小计前 6 31 36% 的 interface

3.2 interface 的"正当"用途

  1. 生成代码(protobuf / buf 编译产物)—— 不可手控
  2. 可扩展性(允许外部 implements)—— 4 个 React props
  3. 历史遗留 —— 5-10 个老代码

3.3 interface 用得少的"原因"

仓库偏好 type 因为: - 联合类型(type X = A | B)必须用 type - 工具类型(Pick<>Omit<>Partial<>)在 type 上更自然 - 映射类型必须用 type - 元组类型必须用 type - 条件类型必须用 type - 统一 type 让 refactor 更简单(interface 改 extends 链,type 改 union)


4. 命名规范

类别 命名 数量
type PascalCase ~2,400 User, Message, Tool
interface PascalCase ~85 PreflightCheckResult, MemoryFile
type with 复数 -s 结尾 ~50 Tools, Messages, Hooks
泛型 <T> 大写单字母 ~80 T, K, V

5. 通用工具类型使用

工具类型 出现次数 用途
Partial<T> 部分字段
Required<T> 必填字段
Pick<T, K> 选字段
Omit<T, K> 排除字段
Record<K, V> 字典
Readonly<T> 只读
ReturnType<typeof F> 函数返回类型
Parameters<typeof F> 函数参数

6. 高级类型模式

模式 出现次数
联合类型 type X = A \| B \| C ~50+
判别联合 type X = { kind: 'a' } \| { kind: 'b' } ~30+
品牌类型 type UserId = string & { __brand: 'UserId' } ~20+
递归类型 type Tree = { children: Tree[] } ~10
条件类型 type X = T extends U ? A : B ~5
infer type X = T extends Promise<infer U> ? U : T ~3
映射类型 type X = { [K in keyof T]: ... } ~5

7. type 优势 vs interface 优势

场景 type 优势 interface 优势
联合类型 ✅ 必须用 type ❌ 不支持
交叉类型 A & B ❌ extends 只能单继承
元组 [A, B] ❌ 不支持
工具类型 ✅ 灵活 ❌ 限制
声明合并 ❌ 不支持 ✅ 自动合并
implements ✅ 可 ✅ 可
性能 略慢(编译时) ✅ 快(可缓存)
错误提示 略差 ✅ 更精准

Claude Code 选 type = 优先灵活性。


8. 关键洞察

  1. 97% 用 type —— 现代 TS 风格,统一 type 让 refactor 简单
  2. 2,477 个 type 定义 —— 大量类型化
  3. interface 仅 85 个 —— 多数是生成代码或历史遗留
  4. 0 个 type 用类名风格 —— 全 PascalCase
  5. 高级类型多 —— 联合、判别、品牌、映射
  6. 少用元组 —— 数据结构多用 interface/object

9. 对比同类 TS 仓库

仓库 type : interface
Claude Code 97 : 3
TypeScript 自身 80 : 20
React 18 70 : 30
旧 jQuery 时代 TS 30 : 70
VSCode 60 : 40

Claude Code 是 极 type 倾向——比 VSCode、React 更甚。


10. 仓库的 type 哲学

"所有类型都用 type——除非要 interface 特性(声明合并、implements 多继承)"

不混用——保持 codebase 一致性: - 减少 mental switching cost - 重构更简单(type 改成 union 不影响其他文件) - 学习曲线更平(只学 type 一种语法)


最后更新:2026-06-06 执行人:devxiaofan