I use a lot of custom events and one blind spot in the typescript static checking is the type of detail in CustomEvent
. A lot of refactorings suffer because of this blind spot. To compensate I have created a global type for CustomEvent
. Since I am using it all over the app I do not want to have imports all over the place just for this type.
globals.d.ts - generic custom event
interface VsCustomEvent<T> extends CustomEvent { detail: T }
I would have expected this to work
handleSomeEvent = ({detail}: CustomEvent<boolean> ) => {
this.doSomething(detail)
}
Is there a better solution than the global generic?
Show activity on this post. let div: HTMLElement | null = document. getElementById("my_div"); let c_event = new CustomEvent<number>("build", {detail: 3}); div. addEventListener("build", function(e: CustomEvent<number>) { // change here Event to CustomEvent console.
Custom events can be created in two ways: Using the Event constructor. Using the CustomEvent constructor.
Returns an integer value that specifies additional information about the event. The returned value depends on the type of the event. For mouse click events, the returned value is the number of clicks.
If I understand the question correctly, you are able to define a base generic globally and then derive actual types from it if needed:
// globals.d.ts
interface CustomEvent<Detail> {
detail: Detail;
}
// some-file.ts
interface BooleanEvent extends CustomEvent<boolean> {}
interface StringEvent extends CustomEvent<string> {}
function handleBoolean({ detail }: BooleanEvent): void {
// `detail` is a boolean
}
function handleString({ detail }: StringEvent): void {
// `detail` is a string
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With