【发布时间】:2018-02-07 15:09:03
【问题描述】:
class Component { }
class ShallowWrapper { }
// generic P is a simple object
class TestContainer<T extends Component, P extends object>
{
constructor(reactElement: T, selectors: P) {
// iterate over selectors and define object properties
}
initialize(): void { }
[elem: keyof P]: any
// I need to define class properties based on P's keys
// -- compiler throws --
// An index signature parameter type cannot be a union type.
// Consider using a mapped object type instead.
}
const p = new TestContainer(new Component, { test: 'a' });
const v = p.test // this throws a type error (property does not exist)
在上面的代码中,我试图根据泛型参数 P 动态定义对象属性。但是编译器会抛出错误
索引签名参数类型不能是联合类型。考虑 改为使用映射对象类型。
我该如何解决这个问题?
【问题讨论】:
标签: typescript generics