Event Handling in TypeScript
This article explains event handling in TypeScript.
You can learn about event handling methods and custom events through code examples.
YouTube Video
Event Handling in TypeScript
Event handling in TypeScript is done in the same way as in JavaScript. However, TypeScript improves type safety, allowing you to safely handle events by using appropriate event types. The basics of event handling involve adding event listeners to DOM elements and executing actions in response to user operations.
Adding Event Listeners
Event listeners are added to DOM elements using the addEventListener
method. For example, to handle a click event, you would do the following:.
1const button = document.getElementById('myButton');
2if (button) {
3 button.addEventListener('click', (event) => {
4 console.log('Button was clicked');
5 });
6}
- In this code,
addEventListener
is used to register a handler for the click event on the specified DOM element.
Event Types in TypeScript
In TypeScript, the event
object received in the event listener is automatically assigned the appropriate type. The event
object has different properties depending on the event type, but its base type is Event
.
By using the appropriate type for each event, you can take advantage of TypeScript's type safety in your development.
Main Event Types
Event
Event
is the base type for common events. Used for things like form submissions or page loading completion.
1const form = document.getElementById('myForm');
2if (form) {
3 form.addEventListener('submit', (event: Event) => {
4 event.preventDefault(); // Prevent the default form submission
5 console.log('Form was submitted');
6 });
7}
- This code detects the form's submit event, prevents the default submit action, and outputs a message to the console instead.
-
MouseEvent
MouseEvent
is an event type related to mouse actions such as clicks and mouse movement. You can get information about the mouse coordinates and which button was clicked.
1const button = document.getElementById('myButton');
2if (button) {
3 button.addEventListener('click', (event: MouseEvent) => {
4 // Log the click position
5 console.log(`Click position: X=${event.clientX}, Y=${event.clientY}`);
6 });
7}
- This code gets the mouse coordinates when the button is clicked and displays them in the console.
KeyboardEvent
KeyboardEvent
is an event type related to keyboard input. You can access the pressed key and the state of modifier keys (Shift, Alt, Ctrl, etc.).
1document.addEventListener('keydown', (event: KeyboardEvent) => {
2 // Log the pressed key
3 console.log(`Key pressed: ${event.key}`);
4 if (event.ctrlKey) {
5 // Log that the Ctrl key was pressed
6 console.log('Ctrl key was pressed');
7 }
8});
- This code displays the name of the key pressed and, if the Ctrl key is held down, also outputs that information to the console.
InputEvent
InputEvent
is an event type related to changes in input fields. It is used when the value of a text field or textarea has changed.
1const input = document.getElementById('myInput') as HTMLInputElement;
2if (input) {
3 input.addEventListener('input', (event: InputEvent) => {
4 // Log the entered value
5 console.log(`Entered value: ${input.value}`);
6 });
7}
- This code displays the content of the input field in the console every time its value changes.
FocusEvent
FocusEvent
is an event type that occurs when an element gains or loses focus.
1const input = document.getElementById('myInput');
2if (input) {
3 input.addEventListener('focus', (event: FocusEvent) => {
4 // Log when the input gains focus
5 console.log('Focused');
6 });
7
8 input.addEventListener('blur', (event: FocusEvent) => {
9 // Log when the input loses focus
10 console.log('Blurred');
11 });
12}
- This code displays "Focused" in the console when the input field is focused, and "Blurred" when it loses focus.
Handling Custom Events with Type Assertion
For custom events or when TypeScript's type inference does not work, you can explicitly specify the type using type assertions.
For example, to handle an event for a specific input field (HTMLInputElement
), specify the type as follows:.
1const input = document.getElementById('myInput') as HTMLInputElement;
2if (input) {
3 input.addEventListener('input', (event: Event) => {
4 const target = event.target as HTMLInputElement;
5 // Log the entered value
6 console.log(`Entered value: ${target.value}`);
7 });
8}
- This code uses type assertion to treat the event target as an
HTMLInputElement
and displays its value in the console.
Removing Event Listeners
You can remove event listeners using removeEventListener
. For this, you need to pass the same event handler that was added initially.
1const button = document.getElementById('myButton');
2
3const handleClick = (event: MouseEvent) => {
4 // Log when the button is clicked
5 console.log('Button was clicked');
6};
7
8if (button) {
9 button.addEventListener('click', handleClick);
10
11 // Remove the event listener later
12 button.removeEventListener('click', handleClick);
13}
- This code adds a click event listener to the button, and then removes it by specifying the same handler.
Creating Custom Events
In TypeScript, in addition to standard events, you can also create and dispatch custom events. Use the CustomEvent
class to create a custom event and trigger it with the dispatchEvent
method.
1const customEvent = new CustomEvent('myCustomEvent', { detail: { name: 'TypeScript' } });
2const div = document.getElementById('myDiv');
3
4if (div) {
5 div.addEventListener('myCustomEvent', (event: CustomEvent) => {
6 // Log when the custom event is fired
7 console.log(`Custom event was triggered: ${event.detail.name}`);
8 });
9
10 div.dispatchEvent(customEvent); // Dispatch the custom event
11}
- This code creates a custom event using
CustomEvent
, dispatches it to the element, and displays its details in the console.
Controlling Event Propagation
When an event occurs, by default it bubbles (propagates to parent elements). To prevent this, use event.stopPropagation()
. You can also use preventDefault()
to prevent the browser's default behavior.
1const button = document.getElementById('myButton');
2if (button) {
3 button.addEventListener('click', (event: MouseEvent) => {
4 event.preventDefault(); // Prevent the default action
5 event.stopPropagation(); // Stop the event propagation
6
7 // Log that event handling has been customized
8 console.log('Custom event handling');
9 });
10}
- This code disables the default action when the button is clicked, stops event bubbling, and executes custom processing.
Summary
Event handling in TypeScript is basically the same as in JavaScript, but with proper type definitions, you can safely and reliably work with event objects and DOM elements. By adding and removing event listeners, applying event types, and using type assertions, you can achieve clearer and less error-prone event handling.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.