【发布时间】:2019-11-22 10:14:38
【问题描述】:
这是一个纯粹的打字稿/泛型问题。我的问题来源于 Angular/CDK (portal.d.ts):
/** Interface that can be used to generically type a class. */
export interface ComponentType<T> {
new (...args: any[]): T;
}
我正在努力解决这个问题,但到目前为止运气不佳。从我写的测试代码可以看出问题:
export interface ComponentType<T> {
new (...args: any[]): T;
}
interface Bar<T> {
getData: () => T
}
class MyBooleanComponent implements Bar<boolean> {
getData(): boolean { return true; }
}
class MyGenericWrapper {
init<T>(comp: ComponentType<T>): T {
return new comp();
}
}
const wrapper = new MyGenericWrapper();
const instance = wrapper.init<boolean>(MyBooleanComponent);
(instance as Bar).getData();
可以看出,这段代码存在一些问题。
首先是MyBooleanComponent,它不能分配给ComponentType<boolean>。我不清楚如何判断 MyBooleanComponent` 返回布尔值?
其次,如果我投射(instance as Bar).getData();,打字稿编译器对Bar 不满意,它想要(instance as Bar<boolean>).getData();,但我希望根据我初始化/设置整个事情的方式,它应该可以推导出boolean 对?
如果我做错事或尝试做不可能的事,我不会使用。任何帮助将不胜感激!
【问题讨论】:
标签: typescript generics typescript-generics