【发布时间】:2021-11-16 19:51:57
【问题描述】:
我有一个带有键 name 和 value 的对象数组。我想将此数组转换为单个对象,其中键是name,值是来自输入对象的value 属性。
type Input = { name: string, value: any }[]
type Output = Record<string, any> // Key-value object { [name]: value }
const input: Input = [
{ name: 'name', value: 'Michal' },
{ name: 'age', value: 24 },
{ name: 'numbers', value: [4, 7, 9] }
]
const getOutput = (input: Input): Output => {
return input.reduce((output, record) => ({ ...output, [record.name]: record.value }), {})
}
// Output is: { name: 'Michal', age: 24, numbers: [4, 7, 9] }
const output: Output = getOutput(input)
上面的例子是有效的,但是我使用Record<string, any> 类型作为输出。这意味着我失去了价值观的类型。有没有办法执行这种转换,但保留类型?
output.age.length // Should be TS error, `number` has no `length` property
output.numbers.length // 3
output.address // Should be TS error, `input` has no `address` property
【问题讨论】:
标签: typescript typescript-generics