TypeScript:如何根据嵌套接口属性动态变更类型并保证类型安全?
TypeScript 类型关联解决方案:根据question.type约束correctAnswerId类型
无需将type字段移至顶层,通过联合类型拆分即可实现correctAnswerId与question.type的类型绑定,保证类型安全,同时避免重复传输字段。
实现代码
export interface IQuestion { type: 'single' | 'sort' prompt: string; options: { id: string, text: string }[] } // 针对不同题型定义细分类型 type SingleCurrentQuestion = { correctAnswerId: string; question: Extract<IQuestion, { type: 'single' }>; extraData?: IResultsAnswerData; } type SortCurrentQuestion = { correctAnswerId: string[]; question: Extract<IQuestion, { type: 'sort' }>; extraData?: IResultsAnswerData; } // 最终的类型为两个细分类型的联合 export type ICurrentQuestion = SingleCurrentQuestion | SortCurrentQuestion;
效果验证
当创建或使用ICurrentQuestion时,TypeScript会自动根据question.type约束correctAnswerId的类型:
// 单选题:correctAnswerId必须是string const singleQuestion: ICurrentQuestion = { correctAnswerId: 'opt-1', question: { type: 'single', prompt: '请选择正确选项', options: [{ id: 'opt-1', text: '选项A' }, { id: 'opt-2', text: '选项B' }] } }; // 排序题:correctAnswerId必须是string[] const sortQuestion: ICurrentQuestion = { correctAnswerId: ['opt-2', 'opt-1'], question: { type: 'sort', prompt: '请按顺序排序', options: [{ id: 'opt-1', text: '第一步' }, { id: 'opt-2', text: '第二步' }] } }; // 类型守卫自动推断类型 function processQuestion(q: ICurrentQuestion) { if (q.question.type === 'single') { // 此处correctAnswerId自动推断为string console.log('单选题答案:', q.correctAnswerId); } else { // 此处correctAnswerId自动推断为string[] console.log('排序题答案:', q.correctAnswerId.join(' → ')); } }
核心优势
- 无需移动
type字段,避免客户端传输重复数据 - 编译期即可检测类型不匹配错误,完全保证类型安全
- 类型守卫场景下自动推断对应类型,无需手动类型断言
内容的提问来源于stack exchange,提问作者Isiah L
相关产品推荐
相关产品推荐

