I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName
and callback
.
public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void {
this.input.addEventListener(eventName, callback);
}
The props object for the listener is a union type of two interfaces: BlurTextFieldCallbackProps
and InputTextFieldCallbackProps
export type TextFieldListenerProps = BlurTextFieldListenerProps | InputTextFieldListenerProps;
export interface BaseTextFieldListenerProps {
eventName: Extract<keyof GlobalEventHandlersEventMap, 'blur' | 'input'>;
callback(e?: FocusEvent | Event): void;
}
export interface BlurTextFieldListenerProps extends BaseTextFieldListenerProps {
eventName: Extract<keyof GlobalEventHandlersEventMap, 'blur'>;
callback(e?: FocusEvent): void;
}
export interface InputTextFieldListenerProps extends BaseTextFieldListenerProps {
eventName: Extract<keyof GlobalEventHandlersEventMap, 'input'>;
callback(e?: Event): void;
}
When I attempt to assign the eventName
and callback
, I encounter this error:
TS2769: No overload matches this call. Overload 1 of 2, '(type: "input" | "blur", listener: (this: HTMLInputElement, ev: Event | FocusEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error. Argument of type '((e?: InputEvent | undefined) => void) | ((e?: FocusEvent | undefined) => void)' is not assignable to parameter of type '(this: HTMLInputElement, ev: Event | FocusEvent) => any'. ...
Initially, I thought there might be an issue if eventName
was `'blur'` and the event was a FocusEvent
. So, I created a typeguard:
export function isBlurTextFieldProps(value: BaseTextFieldListenerProps): value is BlurTextFieldListenerProps {
return value.eventName === 'blur';
}
I then modified the method responsible for setting the event listener:
public setTextFieldInputListener(listenerProps: TextFieldListenerProps): void {
if (isBlurTextFieldProps(listenerProps)) {
this.input.addEventListener(listenerProps.eventName, listenerProps.callback);
}
}
However, this did not resolve the issue :/
My question is:
- Why am I encountering this error?
- How can I resolve it while maintaining strong types? (I am aware that using
any
could fix this, but it's not my preferred approach)