【发布时间】:2021-12-04 17:40:48
【问题描述】:
我有一个数组,其中每个项目都是数组[name: string, someFunction: Function]。我想将它转换为对象,其中键是names,值是someFunctions:
// 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])
}
有什么方法可以连接输入数组中的函数类型和输出对象中的函数类型?
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.
【问题讨论】:
标签: typescript