目标:读懂 AIHom 前端里的 interface、type、union、generic,知道类型是在开发期保护你,不是运行时数据。
前端最常见的类型是“这个对象有哪些字段”。比如消息、工具参数、viewer 配置,都适合用 interface 描述。
interface ToolCallPayload { id: string; name: string; arguments?: Record<string, unknown>; // ? 表示可选 }
协议字段很适合 union。它能防止你把 tool_response 写成 toolResponse 这类拼写错误。
type SocketType = 'request' | 'notification' | 'tool_response';
Promise<T>、Array<T>、Record<K,V> 都是泛型。读法是:外壳固定,里面装什么由尖括号决定。
async function fetchJson<T>(url: string): Promise<T> { const res = await fetch(url); return res.json(); }
TypeScript 只在开发和编译阶段帮你检查。后端真的返回了什么,运行时还要靠接口约定、测试、必要时的字段兜底。全栈联调时不要把 TS 类型当成后端响应保证。
| 看到 | 先问 |
|---|---|
interface XxxProps | 组件需要父级传什么 |
type A = 'x' | 'y' | 这个字段只能取哪些值 |
Promise<Result> | 异步完成后会给什么结果 |
unknown | 这里还不知道结构,使用前要收窄 |
type Status = 'ready' | 'failed' 的作用是?
优先读 TypeScript 官方 Handbook 的 Everyday Types 和 Object Types。