我有一个函数,它接收一个字符串数组,并创建一个对象,其中字符串是键,值是true。
例如:
return keys.reduce((result, key) => {
result[key] = true;
return result;
}, {});
我想使用Typescript键入此函数,以便在使用它时,它会推断返回对象具有键作为来自输入的字符串数组(让我们假设输入始终是静态的)]
有人知道实现此目标的方法吗?我希望这样的工作:
const result = myFunction(['key1', 'key2'])
并使TS将结果识别为具有键:key1和key2的对象
感谢任何帮助者!
此功能可以解决问题(code sample):
const myFunction = <N extends string, T extends readonly N[]>(keys: T) => keys.reduce(
(acc, key) => ({
...acc,
[key]: true
}), {} as { [K in T[number]]: true });
const result = myFunction(['key1', 'key2']) // { key1: true; key2: true; }
当使用N
(as const
)时,可以省略类型参数code sample:
const myFunction = <T extends readonly string[]>(keys: T) => {/* as above */ }
const result = myFunction(['key1', 'key2'] as const) // { key1: true; key2: true; }