0

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 = () => {};
chris
  • 5,365
  • 5
  • 38
  • 52

1 Answers1

0

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

basarat
  • 207,493
  • 46
  • 386
  • 462
  • I read your book all the time :) thank you! Is it possible to infer the return type of some discriminated union based on a parameter? i.e. if code is type A i know the return type would be type B. – chris May 05 '17 at 05:28
  • Yes. All return statements for a union for the return type. e.g. if you return a `string` and a `number` in different sections of your code the return type is inferred to be `string | number` – basarat May 05 '17 at 05:35