aotoyae

[TS] HTML DOM & 이벤트의 타입 설정 본문

TypeScript

[TS] HTML DOM & 이벤트의 타입 설정

aotoyae 2024. 3. 7. 16:47

 

 

💡 js 에서 ts 로 변경할 때,  html DOM 요소들의 타입을 설정하는 방법에 대해 알아보자.

 

✳️ DOM 노드 타입 설정

script.js

const usernameInput = document.getElementById('username');
const submitButton = document.getElementById('submit');

usernameInput.focus();
submitButton.addEventListener('click', handleClick);

function handleClick(e) {
  e.preventDefault();
  const message = `${usernameInput.value}님 반갑습니다.`;
  alert(message);
}

 

script.ts

ts 파일로 바꾸면 타입에러가 나는데 설정해보자.

const usernameInput = document.getElementById('username') as HTMLInputElement; // ** 여기
const submitButton = document.getElementById('submit') as HTMLButtonElement; // ** 여기

usernameInput.focus();
submitButton.addEventListener('click', handleClick);

function handleClick(e: Event) { // ** 여기
  e.preventDefault();
  const message = `${usernameInput.value}님 반갑습니다.`;
  alert(message);
}

 

HTMLElement 까지 입력하면 자동완성이 뜨니

알맞은 타입들을 넣어주면 된다.

 

✳️ 이벤트 타입 설정

이벤트 같은 경우 크게는 Event 타입이 있는데, ✚ SyntheticEvent (이벤트의 조상님)

세부적으로 UIEvent (클릭이나 텍스트 입력), MouseEvent, InputEvent 등이 있다.

 

 

MouseEvent 로 타입을 설정하면 이벤트에서 관련 속성들을 참조할 수 있다.

❗️ 이벤트 import 잊지 말기!

 

어떤 이벤트로 타입을 정할지 헷갈릴 땐

addEventListener 에 인자로 함수를 직접 적어보면 된다!

 

아래 코드도 설정해보자!

 function handleChange(e: any) {
    const { name, value } = e.target;
    const nextValues = {
      ...values,
      [name]: value,
    };
    setValues(nextValues);
  }

 

ChangeEvent 로 설정을 하니 오류가 뜨고 있다.

이벤트 타겟의 타입은 정해주지 않았기 떄문!

제네릭으로 정해주자!

 

  function handleChange(e: ChangeEvent<HTMLInputElement>) {
    const { name, value } = e.target;

 

위에서 본 마우스 이벤트도 버튼을 제네릭에 적어줄 수 있지만

함수 내에서 이벤트 타겟을 쓰고 있지 않으니 생략해도 된다. 🫠

 

✳️ 이벤트 핸들러 자체에 타입을 줘보자.

interface Props {
  className?: string;
  id?: string;
  children?: ReactNode;
  onClick: any; // ** 여기를 바꾸자.
}
onClick: (e: MouseEvent) => void; // 화살표 함수로 이벤트에 타입 지정

onClick: MouseEventHandler; // 리액트에서 제공하는 이벤트핸들러 타입 지정

 

이렇게 두가지 방식으로 바꿀 수 있다.

다른 함수들과 일관되게 가능하면 화살표 함수로 쓰도록 하자!