TypeScript에서 이벤트 처리하기

TypeScript에서 이벤트 처리하기

이 글에서는 타입스크립트에서의 이벤트 처리에 대해 설명합니다.

코드 예제를 통해 이벤트 처리 방법과 커스텀 이벤트에 대해 배울 수 있습니다.

YouTube Video

TypeScript에서 이벤트 처리하기

TypeScript에서의 이벤트 처리는 JavaScript와 동일하게 이루어집니다. 하지만 TypeScript는 타입 안정성을 높여 적절한 이벤트 타입을 사용하여 안전하게 이벤트를 처리할 수 있습니다. 이벤트 처리의 기본은 DOM 요소에 이벤트 리스너를 추가하고, 사용자 동작에 따라 동작을 실행하는 것입니다.

이벤트 리스너 추가하기

addEventListener 메서드를 통해 DOM 요소에 이벤트 리스너를 추가할 수 있습니다. 예를 들어, 클릭 이벤트를 처리하려면 다음과 같이 합니다:.

1const button = document.getElementById('myButton');
2if (button) {
3    button.addEventListener('click', (event) => {
4        console.log('Button was clicked');
5    });
6}
  • 이 코드는 지정된 DOM 요소의 클릭 이벤트에 대해 핸들러를 등록하기 위해 addEventListener를 사용합니다.

TypeScript에서의 이벤트 타입

TypeScript에서는 이벤트 리스너로 전달받는 event 객체에 자동으로 적절한 타입이 할당됩니다. event 객체는 이벤트 타입에 따라 다양한 속성을 가지지만, 기본 타입은 Event입니다.

각 이벤트에 맞는 타입을 사용함으로써 TypeScript의 타입 안정성을 활용할 수 있습니다.

주요 이벤트 타입

  1. Event Event는 일반적인 이벤트의 기본 타입입니다. 폼 제출이나 페이지 로드 완료 등에 사용됩니다.
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}
  • 이 코드는 폼의 submit 이벤트를 감지하고 기본 제출 동작을 막은 후, 대신 콘솔에 메시지를 출력합니다.
  1. MouseEvent

    MouseEvent는 클릭이나 마우스 움직임과 같은 마우스 동작에 관련된 이벤트 타입입니다. 마우스 좌표, 클릭된 버튼 등의 정보를 얻을 수 있습니다.

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}
  • 이 코드는 버튼을 클릭했을 때 마우스 좌표를 가져와 콘솔에 표시합니다.
  1. KeyboardEvent KeyboardEvent는 키보드 입력에 관련된 이벤트 타입입니다. 눌린 키와 Shift, Alt, Ctrl 등 보조 키의 상태를 확인할 수 있습니다.
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});
  • 이 코드는 누른 키의 이름을 표시하고, Ctrl 키가 눌려 있을 경우 해당 정보도 콘솔에 출력합니다.
  1. InputEvent InputEvent는 입력 필드의 변경과 관련된 이벤트 타입입니다. 텍스트 필드나 textarea의 값이 변경되었을 때 사용됩니다.
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}
  • 이 코드는 입력 필드의 값이 바뀔 때마다 그 내용을 콘솔에 표시합니다.
  1. FocusEvent FocusEvent는 요소가 포커스를 얻거나 잃었을 때 발생하는 이벤트 타입입니다.
 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}
  • 이 코드는 입력 필드가 포커스를 받을 때 콘솔에 "Focused"를, 포커스를 잃을 때는 "Blurred"를 표시합니다.

타입 단언을 통한 커스텀 이벤트 처리

커스텀 이벤트이거나 TypeScript의 타입 추론이 동작하지 않을 경우, 타입 단언을 통해 명시적으로 타입을 지정할 수 있습니다.

예를 들어, 특정 입력 필드(HTMLInputElement)의 이벤트를 처리하려면 다음과 같이 타입을 지정합니다:.

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}
  • 이 코드는 타입 단언을 사용하여 이벤트 타겟을 HTMLInputElement로 간주하고 그 값을 콘솔에 표시합니다.

이벤트 리스너 제거하기

removeEventListener를 사용하여 이벤트 리스너를 제거할 수 있습니다. 이때는 처음에 추가했던 것과 동일한 이벤트 핸들러를 전달해야 합니다.

 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}
  • 이 코드는 버튼에 클릭 이벤트 리스너를 추가하고, 동일한 핸들러를 지정하여 이벤트 리스너를 제거합니다.

커스텀 이벤트 생성하기

TypeScript에서는 표준 이벤트뿐만 아니라 커스텀 이벤트를 생성하고 발생시킬 수도 있습니다. CustomEvent 클래스를 사용해 커스텀 이벤트를 만들고, dispatchEvent 메서드로 이를 발생시킬 수 있습니다.

 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}
  • 이 코드는 CustomEvent를 사용하여 커스텀 이벤트를 생성하고, 해당 요소에 디스패치한 후 상세 정보를 콘솔에 표시합니다.

이벤트 전파 제어하기

이벤트가 발생하면, 기본적으로 상위 요소로 전파(버블링)됩니다. 이를 막으려면 event.stopPropagation()을 사용하세요. preventDefault()를 사용해 브라우저의 기본 동작을 막을 수도 있습니다.

 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}
  • 이 코드는 버튼 클릭 시 기본 동작을 막고 이벤트 버블링을 중단하며, 커스텀 처리를 실행합니다.

요약

TypeScript에서의 이벤트 처리는 기본적으로 JavaScript와 같지만, 적절한 타입 정의를 통해 이벤트 객체와 DOM 요소를 더욱 안전하고 신뢰성 있게 다룰 수 있습니다. 이벤트 리스너 추가 및 제거, 이벤트 타입 적용, 그리고 타입 단언을 통해 더 명확하고 오류가 적은 이벤트 처리가 가능합니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video