Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: function return type based on argument, without overloading

Is it possible to return a function's type based on an argument?

I saw Variable return types based on string literal type argument, but it uses overloading. Here, I have 100+ types, so I do not want to do overloading.

interface Registry {
    A: number,
    B: string,
    C: boolean,
    // ... 100 more types like this
}

function createType<T = Registry[typeof myType]>(myType: keyof Registry, value: any): T {
    // do some magic
    // ...
    return value;
}

const a = createType('A', 2); // Expected type: number. Actual: error above

Playground Link

like image 830
jeanpaul62 Avatar asked Jul 25 '19 10:07

jeanpaul62


1 Answers

You can do it, but you will need a type parameter to capture the argument passed in. With this new type parameter you can index into your Registry to get the type you want:

interface Registry {
    A: number,
    B: string,
    C: boolean
}

function createType<K extends keyof Registry>(type: K, value: Registry[K]): Registry[K] {
    return value;
}

const a = createType('A', 2); // ok 
const b = createType('B', 2); // err

like image 98
Titian Cernicova-Dragomir Avatar answered Oct 23 '22 03:10

Titian Cernicova-Dragomir