Is it feasible in TypeScript to infer the return type of a function based on its arguments? This feature would be beneficial when extracting specific properties from, for example, a database query.
Here is an illustration (https://repl.it/repls/IrresponsibleUnsightlySequences#index.ts) :
type QueryReturnType = {
a: string;
b: number;
c: boolean;
};
const queryFunc = (): QueryReturnType => {
return {
a: 'b',
b: 1,
c: true,
};
};
type Params = {
[key: string]: keyof QueryReturnType;
};
const takeQuerySubset = (params: Params) => {
const res: any = {};
Object.keys(params).map((key) => {
res[`${key}`] = queryFunc()[params[key]];
});
return res;
};
takeQuerySubset({ test1: 'a' }); // { test1: 'b' }
takeQuerySubset({ test2: 'b' }); // { test2: '1' }
takeQuerySubset({ test3: 'b', test4: 'c' }); // { test3: '1', test4: true }
Although the current implementation works, the type of takeQuerySubset is: (params: Params) => any
, whereas the objective is to derive a return type dynamically based on the parameters i.e.:
takeQuerySubset({ test1: 'a' }); // should return {test1: string}
takeQuerySubset({ test2: 'b' }); // should return {test2: number}
takeQuerySubset({ test3: 'b', test4: 'c' }) // should return {test3: number, test4: boolean}
This approach ensures that another function utilizing takeQuerySubset can accurately predict the output received.
I attempted using generics to replace any
without success.
Additionally, note that variables have been renamed e.g. a
is now referred to as test1
, b
as test2
, etc.