我有一个通用类,可以是两个不同类的实例。 在构造函数中,类用户必须传递要使用的实例的类型,然后在映射对象中,我使用此类型来获取相应的类。
尽管进行了高级键入,流仍抱怨我无法存储实例,因为实例X与实例Y不兼容。
type BrowserHistoryInstance = {|
+foo: (number) => number
|};
type MemoryHistoryInstance = {|
+bar: (number) => number
|};
const historyTypeMaps = Object.freeze({
memory : (({}: any): MemoryHistoryInstance),
browser : (({}: any): BrowserHistoryInstance)
});
class History <InstanceType: $Keys<typeof historyTypeMaps>> {
instance: $ElementType<typeof historyTypeMaps, InstanceType>;
constructor(type: InstanceType) {
this.instance = historyTypeMaps[type];
}
}
错误:
this.instance = historyTypeMaps[type];
^ Cannot assign `historyTypeMaps[type]` to `this.instance` because property `memo` is missing
in `BrowserHistoryInstance` [1] but exists in `MemoryHistoryInstance` [2].
References:
browser : (({}: any): BrowserHistoryInstance)
^ [1]
memory : (({}: any): MemoryHistoryInstance),
^ [2]