TypeScript中如何实现对象属性值联动的类型校验
TypeScript 对象属性关联校验实现方法
你当前的代码里,Status 接口的 id 和 name 是独立的类型,会出现 id=1 但 name='Awaiting' 这种不匹配的情况。要实现属性值的严格对应,得把每个合法的 id 和 name 组合绑定起来,具体做法如下:
正确实现代码
const StatusTypes = [ { id: 1, name: 'Failed', }, { id: 2, name: 'Awaiting', }, ] as const; // 直接从数组推导每个合法的状态组合类型 type StatusItem = typeof StatusTypes[number]; // 把状态组合和公共属性交叉,得到最终的Status类型 export type Status = StatusItem & { desc: string; count: number | null; }; // 合法示例 const validStatus1: Status = { id: 1, name: 'Failed', // 与id=1匹配,符合要求 desc: '请求失败', count: 5 }; // 非法示例(会触发TypeScript报错) const invalidStatus: Status = { id: 1, name: 'Awaiting', // id=1时name只能是'Failed',此处不匹配 desc: '等待中', count: 10 };
原理说明
as const让TypeScript将数组内的所有值识别为字面量类型,而非宽泛的number或string,保留了值的具体信息。typeof StatusTypes[number]会推导出一个联合类型:{ id: 1; name: 'Failed'; } | { id: 2; name: 'Awaiting'; },每个分支里的id和name是绑定死的关联关系。- 最后通过交叉类型,把状态组合和公共字段(
desc、count)合并,得到的Status类型会自动校验id与name的匹配性,不符合组合规则的赋值会直接触发编译报错。
内容的提问来源于stack exchange,提问作者user1264429
相关产品推荐
相关产品推荐

