Given two different handling functions which handle two different types of objects with a shared base interface, I want to create a mapping between the type enum and the handlers. If the GenericHandler.handle()
is defined as an anonymous function the code won't compile (Type 'EventType' is not assignable to type 'EventType.A'.
on the mapping attributes). However simply changing the interface to what I understand to be exactly equivalent fixes the issue:
interface GenericHandlerInterface<T extends Base = Base> {
handle(args: { event: T }): void;
}
What causes this difference?
Full example:
enum EventType {
A = 'A',
B = 'B',
}
interface Base {
type: EventType;
}
interface A extends Base {
type: EventType.A;
}
interface B extends Base {
type: EventType.B;
}
const aHandlerInterface: GenericHandlerInterface<A> = {
handle: ({ event }) => {
console.log(event);
},
};
const bHandlerInterface: GenericHandlerInterface<B> = {
handle: ({ event }) => {
console.log(event);
},
};
const handlerMappingInterface: { [key in EventType]: GenericHandlerInterface } = {
[EventType.A]: aHandlerInterface,
[EventType.B]: bHandlerInterface,
};
interface GenericHandlerInterface<T extends Base = Base> {
handle: (args: { event: T }) => void;
}