I'm currently in the process of developing various web components, each capable of emitting custom events. To illustrate, here are a couple of straightforward examples:
//MyButton
emits 'myButtonPressed' with the following details:
interface ButtonDetailType {
id: string;
}
//MySlider
emits 'mySliderChanging' with details including:
interface SliderChangingDetailType {
id: string;
value: number;
}
and also emits 'mySliderChanged' with the following details:
interface SliderChangedDetailType {
id: string;
oldValue: number;
newValue: number;
}
When it comes to listening for these events, my code typically resembles the following:
buttonEl.addEventListener( 'myButtonPressed', ( event : CustomEvent ) => {
const detail = event.detail as ButtonDetailType;
//now I have access to detail.id
} );
sliderEl.addEventListener( 'mySliderChanging', ( event : CustomEvent ) => {
const detail = event.detail as SliderChangingDetailType;
//now I have access to both detail.id and detail.value
} );
With an increasing number of components being developed, I've found myself struggling to keep track of all the custom event names associated with each component, as well as their respective detail types.
To address this challenge, I've been contemplating the creation of an object containing all pertinent information, like so:
EVENTS = {
button: {
myButtonPressed: 'myButtonPressed',
detailType: 'ButtonDetailType',
},
slider: {
mySliderChanged': 'mySliderChanged',
detailTypes: [
'SliderChangedDetailType',
'SliderChangingDetailType',
]
}
};
This approach enables me to easily access all available event names for each component, with the added assistance of auto-complete functionality as I type:
buttonEl.addEventListener( EVENTS.button. //autocomplete provides a list of event names here! YAY!
sliderEl.addEventListener( EVENTS.slider. //similar autocomplete functionality here too!
However, an issue arises when attempting to convert a string into a type. Ideally, I'd be able to achieve something like this:
buttonEl.addEventListener( EVENTS.button.myButtonPressed, ( event : CustomEvent ) => {
const detail = event.detail as EVENTS.button.detailType; // <- unfortunately invalid: EVENTS.button.detailType is a string rather than a type!
} );
Is there a way to convert strings into types within TypeScript?