When developing my functions, I aim to provide flexibility for consumers to use a wider type. However, I encounter issues when the type is used in a contravariant position and TypeScript raises complaints.
Here is the simplified code snippet:
function wrapper<T extends Event = Event>(node: HTMLElement) {
const handler = (e: T) => console.log(e.cancelable);
node.addEventListener("click", handler);
}
An error occurs with the following message:
Type 'Event' is not assignable to type 'T'. 'Event' can be assigned to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Event'.
I am seeking guidance on how to express my intention so that TypeScript can better understand it.
Full code snippet:
export function tracker(
eventType: string,
options?: boolean | AddEventListenerOptions
) {
const stream: Stream<Event> = Stream.empty();
function tracker(node: HTMLElement) {
const handler = (event: Event) => stream.shamefullySendNext(event);
node.addEventListener( eventType, handler, options);
return {
destroy: () => {
node.removeEventListener(eventType, handler);
stream.shamefullySendComplete();
},
};
}
return {
stream,
tracker,
};
}