6
votes

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

1

1 Answers

6
votes

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