Return different type by string in Typescript
typescript, typescript-generics
Solution
Create an overloaded declaration like so
interface Type1 { typeName: string; };
interface Type2 { typeVersion: string; };
type AllTypes = Type1 | Type2;
function returnTypes(t: 'type1'): Type1;
function returnTypes(t: 'type2'): Type2;
function returnTypes(t : 'type1' | 'type2'): AllTypes {
switch (t) {
case "type1": return { typeName: "test" };
case "type2": return { typeVersion: "test" };
}
}
console.log(returnTypes('type1').typeName);
console.log(returnTypes('type2').typeVersion);
Playground Link
Note that when you overload a function in this manner, the implementation signature is not available to callers. Only the declarations specified beforehand comprise an overloaded function's interface.
UPDATE: Fixed and completed example to show that TypeScript knows which type it is returning.
Problem
Given we have two different types as below, how can we change the return of function based on a string parameter and not providing the generic type? ``` interface Type1 { typeName: string; }; interface Type2 { typeVersion: string; }; type AllTypes = Type1 | Type2; function returnTypes(t: string): AllTypes { ... } const typeResult = returnTypes('type1'); console.log(typeResult.typeName); ``` Here the return is not defined!