Reputation: 6823
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
const getInstance = () => {};
Upvotes: 1
Views: 2900
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.
Upvotes: 1