惯用的打字稿枚举可区分联合

Idiomatic Typescript Enum Discriminated Union

从 typescript 2.0 开始,您可以使用带枚举的可区分联合作为判别式,如下所示:

export function getInstance(code: Enum.Type1, someParam: OtherType1): MyReturnType1;
export function getInstance(code: Enum.Type2, someParam: OtherType2): MyReturnType2;
export function getInstance(code: Enum, someParam: UnionOfOtherTypes): UnionOfReturnTypes {
  switch (code) {
    case Enum.Type1:
      return new ReturnType1(someParam as OtherType1);
    case Enum.Type2:
      return new ReturnType2(someParam as OtherType2);
  }
}

从 TypeScript 2.3 开始

Is this the idiomatic way to do this

没有。如果您需要使用类型断言,例如someParam as OtherType1 不安全。

更多