检查变量是否属于具有相同属性的 Typescript 中的自定义类型

Check if variable belongs to custom type in Typescript with same properties

有以下几种类型:

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;

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

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

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

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

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