【问题标题】:How can I create a generic type for a dynamic generated object created from an array如何为从数组创建的动态生成对象创建泛型类型
【发布时间】:2019-06-11 05:01:21
【问题描述】:
我正在尝试为从道具数组生成对象的函数生成类型定义,但我遇到了问题。
问题是在{ [K in T]: boolean } 中,我无法遍历类型 T。
这是我想要做的:
const createObject = <T extends string[]>(props: T): { [K in T]: boolean } => {
return props.reduce((acc: any, prop: string) => {
acc[prop] = true
return acc
}, {})
}
谢谢
【问题讨论】:
标签:
typescript
generics
string-literals
typescript-generics
【解决方案1】:
只是一点点解决方法......你在这里
const createObject = <T extends string>(props: T[]): {[K in T]: boolean} => {
return props.reduce((acc: any, prop: string) => {
acc[prop] = true;
return acc;
}, {});
};
const testObj = createObject(['one', 'two']);
const one = testObj.one;
const two = testObj.two;
const three = testObj.three; // ERROR