【问题标题】:Check if variable belongs to custom type in Typescript with same properties检查变量是否属于具有相同属性的 Typescript 中的自定义类型
【发布时间】:2020-04-17 10:01:22
【问题描述】:

有以下几种:

type TypeA = {
  desc: string;
  name: string;
}

type TypeB = {
  desc: string;
  name: string;
  age: number;
}

type TypeC = {
  desc: string;
  name: string;
  age: number;  
  gender: string;  
}

type TypeAll = TypeA | TypeB | TypeC;

我搜索了解决方案,发现 Typeguard 是检查自定义类型的最优雅的方法。但是在所有示例中,它们都会过滤该类型的显式属性。喜欢:

isTypeC(type: TypeAll):type is TypeC {
  return type.gender !== undefined
}    

TypeA 或 TypeB 怎么写? 此外,类型可能会随着时间而改变(而不是在运行时!),这需要一个不检查显式属性的解决方案。这可能吗?

【问题讨论】:

    标签: typescript types typeguards


    【解决方案1】:

    在运行时,您所拥有的只是“原始”JSON 对象。因此,除了检查有效负载之外,您没有任何其他方式来断言其类型。通常人们会使用某种“标记”属性来安全地区分这些不同的类型,并避免混淆具有重叠属性的类型:

    type TypeA = {
      type: "A";
      desc: string;
      name: string;
    }
    
    type TypeB = {
      type: "B";
      desc: string;
      name: string;
      age: number;
    }
    
    type TypeC = {
      type: "B";
      desc: string;
      name: string;
      age: number;  
      gender: string;  
    }
    
    type TypeAll = TypeA | TypeB | TypeC;
    

    这种设计模式被称为“Discriminated Unions”,the Typescript Handbook documents the intended usage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 1970-01-01
      • 2022-01-25
      • 2020-07-17
      • 2010-12-25
      • 2022-01-26
      相关资源
      最近更新 更多