Search code examples
typescriptenumsidiomsdiscriminated-union

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

  • Is this the idiomatic way to do this?
  • Are we able to infer the type of someParam without casting?
  • Are we able to simplify the type definitions, maybe using generics, altering the function parameters, etc so we only need to define the final function?
  • Is it possible declare the functions as consts like: const getInstance = () => {};

Solution

  • 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