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
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
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