I need to write in typeScript types for a function that accepts a config object, in the properties of which functions are written, and returns an object with the same properties as the config, but the values ​​contain the result of the function:

function init (config) { return Object .keys(config) .reduce((prev, key)=> { prev[key] = config[key]() return prev }, {}) } 

Tell me, please, how can TypeScript describe the type of such a function?

Those. The init function will be a library, and other developers will be able to call it, for example, like this:

 let temp = init({a:()=>5 as number, b:()=>[3,4] as number[]}). 

Then the object will be recorded in temp {a: 5, b: [3,4]} , and I want typescript to automatically deduce its (temp) types, and swear, for example, to call temp.a.map () t. to. The temp property of the object 'a' is a number, not an array. In the parameter of the function init in the property 'a' there was a function that returns a number, therefore after the execution of the function init there will be a number. I want to understand how you can specify the types for the init function, what would it work ...

  • It depends on which types will return functions. And show the type for the config . - Stepan Kasyanenko
  • @Stepan Kasyanenko, the idea is that the config is of the type of {[K: string]: () => any}, and the output will be {, [K: string]: any}, respectively. But the problem is in any, I want ts to somehow output the type according to the parameter that I passed. Those. if I pass init ({test: () => 5}). test.map, then ts would deduce that the function will return an object for which the test property is a number, and would give an error that the number does not have the map property - vvtvvtvvt1
  • Without an explicit indication of the types, this will not work, as far as I know. - Stepan Kasyanenko
  • @StepanKasyanenko, is it possible to declare a type for a function like in ts - type TA = () => number; and then, by some construction, indicate that type TB has a type that is equal to the result of performing TA. Those. something like type TB = TA (). Or so it can not be done in any way? - vvtvvtvvt1
  • add to the question more information about where what types are expected. - Grundy

1 answer 1

Together we found:

 function init<T extends { [k: string]: () => any }>(config: T):{[r in keyof T]:ReturnType<T[r]>} {....} 

And it works, after a call, for example

 let temp = init({a:()=>5 as number, b:()=>[3,4] as number[]}). 

TypeScript will automatically display the type {a: number, b: number []} for temp and you can work normally with the result of the function.