TypeScript联合类型区分:如何通过属性判断而非新增标识字段
如何在TypeScript中通过属性存在性区分无标识字段的联合类型
针对你的场景,不需要新增type_name这类标识字段,有两种直接可行的方案:
方案一:使用in操作符类型守卫
这是最简洁的方式,TypeScript原生支持通过in操作符的检查来自动收窄联合类型:
type InputA = { name: string content: string color: string } type InputB = { name: string content: number } type Input = InputA | InputB function foo(input: Input) { // 通过'in'操作符检查属性存在性,TypeScript会自动收窄类型 const color = 'color' in input ? input.color : undefined; // 此时在条件分支中,input会被正确识别为InputA/InputB }
当'color' in input为true时,TypeScript会自动推断input的类型为InputA,此时访问input.color完全合法;为false时则推断为InputB,返回undefined。
方案二:自定义类型守卫函数
如果需要更严谨的类型校验(比如额外验证color的类型),可以自定义类型守卫函数:
function isInputA(input: Input): input is InputA { // 同时检查属性存在性和类型,确保类型准确性 return 'color' in input && typeof (input as InputA).color === 'string'; } function foo(input: Input) { const color = isInputA(input) ? input.color : undefined; }
通过input is InputA这个返回类型注解,TypeScript会在isInputA(input)返回true时,将input的类型收窄为InputA,后续访问input.color不会触发编译错误。这种方式适合需要复杂判断逻辑的场景。
内容的提问来源于stack exchange,提问作者47ndr
相关产品推荐
相关产品推荐

