chris
chris

Reputation: 6823

Idiomatic Typescript Enum Discriminated Union

As of typescript 2.0 you can use discriminated unions with an enum as the discriminant like this:

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);
  }
}

As of TypeScript 2.3

Upvotes: 1

Views: 2900

Answers (1)

basarat
basarat

Reputation: 275819

Is this the idiomatic way to do this

No. if you need to use a type assertion e.g. someParam as OtherType1 it is unsafe.

More

Upvotes: 1

Related Questions