我正在尝试为我的应用程序构建自定义事件机制,并且正在努力为其定义准确的类型。恕我直言,这些类型应该正确,但是Typescript似乎无法推断出侦听器数组的正确类型。当我将监听器数组声明为const listeners = eventlisteners[kind] as XEventlistener<T>[]
时,它可以工作,但是我不太喜欢Typescript中的声明。有人可以解释为什么Typescript无法为该数组推断正确的类型吗?还是我的打字错误?这是代码:
export const enum XEventTypes {
CONFIG_UPDATE,
ACTION_FINISHED
}
export type XEventListenerCollection = {
[T in XEventTypes]: XEventListener<T>[];
};
export interface XEvent<S extends XEventTypes> {
kind: S;
detail: DetailTypes[S];
}
export interface DetailTypes {
[XEventTypes.CONFIG_UPDATE]: string;
[XEventTypes.ACTION_FINISHED]: number;
}
export type XEventListener<T extends XEventTypes> = (event: XEvent<T>) => void;
const eventListeners: XEventListenerCollection = {
[XEventTypes.CONFIG_UPDATE]: [],
[XEventTypes.ACTION_FINISHED]: []
};
export function addEventListener<T extends XEventTypes>(kind: T, listener: XEventListener<T>): void {
// this doesn't compile without the assertion
const listeners = eventListeners[kind] as XEventListener<T>[];
if (listeners.indexOf(listener) > -1) {
return;
}
listeners.push(listener);
}