组件和接口边界
前端类型最有价值的地方是边界:组件 Props、事件负载、路由参数和接口响应。类型声明只能约束编译器看到的调用者,不能验证浏览器收到的 JSON。
ts
type Product = { id: string; price: number };
type ProductCardProps = {
product: Product;
onAdd: (id: string) => void;
};在边界先把 unknown 校验成领域类型,再把领域类型传给组件。这样组件不需要重复检查字段,也不会因为一个后端字段拼写变化而静默显示空白。
运行时校验的最小形式
ts
function isProduct(value: unknown): value is Product {
if (typeof value !== 'object' || value === null) return false;
const record = value as Record<string, unknown>;
return typeof record.id === 'string' && typeof record.price === 'number';
}真实项目可以使用专门 schema 库,但原则不变:校验发生在不可信数据进入业务状态之前。
练习
为列表接口写 decodeProducts(value: unknown): Product[]。它必须检查数组、每个元素的 id 和 price,并在首个非法元素处抛出包含索引的错误。