Exploring TypeScript is a fresh yet exciting journey for me!
In the world of JavaScript, checking if an object has a function and then calling it can be achieved with code like this:
if(this['my_func']) {
this['my_func']();
}
However, in TypeScript, things don't seem to flow the same way. For the given code to be valid, my_func
must be explicitly declared. In my scenario, whether my_func
should be declared or not is up to a subclass's discretion. I wish for it to be invoked only when it is defined.
I am aware that I could use @ts-ignore
, but I am on the lookout for a more elegant solution.
Is there a method to indicate that an object might have undeclared declarations?
Below is the complete code snippet:
import {LitElement} from 'lit';
export type AnyConstructor<T = object> = new(...args: any[]) => T;
type EventType = keyof HTMLElementEventMap;
type EventValue = ValueOf<HTMLElementEventMap>;
export abstract class EventClass extends LitElement {
}
export const EventMixin = <T extends AnyConstructor<EventClass>>(
events: EventType[],
superClass: T
): T & AnyConstructor<EventClass> => {
class Event_ extends superClass {
public override connectedCallback(): void {
super.connectedCallback();
events.forEach((event: EventType) => {
const listener: any = this[`_${event}`];
if(listener) {
this.addEventListener(event, (event: EventValue) => listener(event));
}
});
}
}
return Event_;
};
The intention here is to empower a subclass to define functions like _onClick(event: MouseEvent)
, which are set as listeners upon connecting. This approach may not be optimal, I understand. My exploration with TypeScript is ongoing, and I welcome any constructive feedback or suggestions!