Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the type of CustomEvent detail property in typescript

Tags:

typescript

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?

like image 279
Adrian Moisa Avatar asked Dec 09 '17 10:12

Adrian Moisa


People also ask

How do I use a custom event in typescript?

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.

What are the two types of custom events?

Custom events can be created in two ways: Using the Event constructor. Using the CustomEvent constructor.

What is event detail in JS?

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.


1 Answers

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
}
like image 76
Dima Parzhitsky Avatar answered Sep 29 '22 10:09

Dima Parzhitsky