I have array where each item is array [name: string, someFunction: Function]
. I would like to convert it to object, where keys are name
s and values are someFunction
s:
// Input
const arrayFunctions = [
['getLength', (text: string) => text.length],
['setValue', (id: string, value: number) => {}],
['getAll', () => ([1, 2, 3])]
]
// Output
const objectFunctions = {
getLength: (text: string) => text.length,
setValue: (id: string, value: number) => {},
getAll: () => ([1, 2, 3])
}
Is there any way to connect type of function in input array and type of function in output object?
type ObjectFunctions<ArrayFunctions> = { [/* Value from ArrayFunctions[i][0] */]: /* Value from ArrayFunctions[i][1] */ }
const arrayToObject = <ArrayFunctions extends Array<any>>(functions: ArrayFunctions) => {
const result = {}
for (const [name, func] of functions) {
result[name] = func
}
return result as ObjectFunctions<ArrayFunctions>
}
const arrayFunctions = [
['getLength', (text: string) => text.length],
['setValue', (id: string, value: number) => {}],
['getAll', () => ([1, 2, 3])]
]
const objectFunctions = arrayToObject(arrayFunctions)
const length = objectFunctions.getLength() // Should be error because first parameter (text) is missing.
objectFunctions.setValue(true, 2) // Should be error, because of first parameter (id) must be string.