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!
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With