Return different type by string in Typescript

Viewed 7094

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!

4 Answers

Let's say I have an array of objects with different types. All objects have the same field ID. My task is to extract one object by ID. And I want to make sure that object has specific type. I don't want to use question marks in my types.

Here is my solution -

interface Object1 { 
    id: string;
    color: string; 
};

interface Object2 { 
    id: string;
    age: number; 
};

type ObjectType = Object1 | Object2;

function getObject(arr: any, id: '101'): Object1;

function getObject(arr: any, id: '102'): Object2;

function getObject(arr: any, id : '101' | '102'): ObjectType {
    return arr.find((item) => item.id === id);
}

const arr = [
    {
        id: '101',
        color: 'white',
    },
    {
        id: '102',
        age: 12,
    }
]

console.log(getObject(arr, '101').color);
console.log(getObject(arr, '102').age);
Related