Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return different type by string in Typescript

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!

like image 382
PRAISER Avatar asked May 13 '17 23:05

PRAISER


Video Answer


1 Answers

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.

like image 133
Aluan Haddad Avatar answered Sep 21 '22 22:09

Aluan Haddad