TypeScript로 DOM 조작하기

YuJin Lee·2021년 11월 1일
0

TypeScript

목록 보기
2/2

출처: https://youtu.be/iZjfnoF784k
코딩애플 - TypeScript로 웹개발하려면 HTML 조지는법을 알아야


html, tsconfig.json 파일을 아래와 같이 세팅한다.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h4 id="title">안녕하세요</h4>
  <a href="naver.com" class="link">링크</a>
  <button id="button">버튼</button>

  <script src="./index.js"></script>
</body>
</html>

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
  }
}

TypeScript로 DOM 조작하기

객체를 선택한 후 바로 조작하려고 하면 에러가 난다.
선택한 객체가 null 값일 수 있는 union 타입이기 때문이다.

let title = document.querySelector('#title');
title.innerHTML = '반가워요'; // title이 null 값일 수 있는 union 타입이기 때문에 에러

TypeScript로 DOM을 조작할 수 있는 방법은 다음과 같다.

if문으로 오브젝트가 null인지 아닌지 확인하기

null이 아닐 때만 DOM을 조작한다.

if (title != null) {
  title.innerHTML = '반가워요';
}

if문으로 오브젝트가 클래스의 인스턴스인지 확인하기

인스턴스가 맞을 때만 DOM을 조작한다.

if (title instanceof Element) {
  title.innerHTML = '반가워요';
}

위 가장 많이 쓰이는 방법인데, 왜냐하면 narrowing을 가장 상세하게 해줄 수 있기 때문이다.
예를 들어 a태그의 경우 그냥 Element가 아닌 HTMLAnchorElement로 확인을 해야 true가 된다.

TypeScript가 제공하는 HTML관련 타입들이 있는데, 대표적인 Element 타입과 HTMLAnchorElement, HTMLHeadingElement, HTMLButtonElement 등의 세부타입이 있다.
해당 타입에는 어떤 속성을 쓸 수 있는지 등의 내용이 정의되어 있다.

let link = document.querySelector('.link');
if(link instanceof HTMLAnchorElement) {
  link.href = 'www.kakao.com';
}

title 이란 요소를 Element로 간주

TypeScirpt를 쓰는 의미가 없어지기 때문에 비상시 또는 100% 확신할 때만 써야 한다.

let title = document.querySelector('#title') as Element;
title.innerHTML = '반가워요';

optional chaining을 사용하여 오브젝트가 null인지 확인

오브젝트 뒤에 ?를 붙이면 해당 값이 있을 때는 출력해주고, 없으면 undefined를 출력한다.
optional chaining은 2020년 이후부터 쓸 수 있는 문법이다.

if (title?.innerHTML) {
  title.innerHTML = '반가워요';
}

tsconfig.json의 strict 모드를 false로 한다.

narrowing을 하지 않아도 에러가 나지 않는다.

+ 그냥 자바스크립트 쓸 때도 아래와 같이 narrowing을 해주는 것이 좋다.

if (title?.innerHTML != undefined) {
  title.innerHTML = '반가워요';
}
profile
배운 것을 기록하는 곳 💻🙂

0개의 댓글