I am trying to use extends in a generic parameter to index an object but I'm getting the following error:
Argument of type 'IHandlerMap[K]' is not assignable to parameter of type 'BasicHandler'. Type 'BasicHandler | KeyPressHandler' is not assignable to type 'BasicHandler'. Type 'KeyPressHandler' is not assignable to type 'BasicHandler'.ts(2345)
Code:
export type BasicHandler = () => void;
export type KeyPressHandler = (keyCode: number) => void;
interface IHandlerMap {
OnTick: BasicHandler;
OnKeyDown: KeyPressHandler;
}
type HandlersType = {[key in keyof IHandlerMap]: IHandlerMap[key][]};
export class EventManager {
private readonly handlers: HandlersType = {
OnTick: [],
OnKeyDown: [],
};
public addHandler<K extends keyof IHandlerMap>(
type: K,
handler: IHandlerMap[K]
): {
this.handlers[type].push(handler); // Error is occuring here.
}
}
It appears that TS is only able to deduce that the object property is an array of BasicHandler types when it can be BasicHandler OR KeyPressHandler?
How do I use keyof to index an interface (handler: IHandlerMap[K]) and then use that parameter to push to a object key that is also type'd (this.handlers[type].push(handler)?
I'm having a lot of trouble explaining what I'm trying to do, is this the wrong way to go about doing this? If so, what is an alternative?
anyfor now. I hope @jcalz will check it out. - Maciej Sikora