[TypeScript]Use Custom event

This article can be read in about 2 minutes.
PR

The purpose 


To dispatch a custom event in TypeScript and trigger a process based on that event.

PR

Implementation

Dispatch event

Here’s how you can dispatch the event with the code you’ve provided:

const event = new CustomEvent("event_name", { detail: { val1: "value 1", val2: "value 2" } });
dispatchEvent(event);

The "event_name" can be changed to any name you like.

The contents of the detail object can also be freely modified.

Receive event


Receiving the event is done as follows:

addEventListener("event_name", (e) => {
        console.log ((e as CustomEvent).detail.val1+ (e as CustomEvent).detail.val2));
    })

Change "event_name" to the name of the event you dispatched.


If you try to access e.detail directly without casting it as CustomEvent (e.g., e.detail), TypeScript will throw an error: “Property ‘detail’ does not exist on type ‘Event’.” This error will not occur in plain JavaScript.

PR

Result


You’ve successfully learned how to send and receive any custom event in TypeScript.

PR

Reference

イベントの作成と起動 - イベントリファレンス | MDN
この記事では、 DOM イベントを作成して処理する方法を説明します。このようなイベントは、一般に、ブラウザー自体によって起動されたイベントとは対照的に、合成イベントと呼ばれます。

comment

Copied title and URL