잠온다

TS) Typescript로 HTML 변경 및 조작할 때 주의점 본문

Typescript

TS) Typescript로 HTML 변경 및 조작할 때 주의점

블블디 2022. 5. 30. 22:43

1. 예제1

// tsconfig.json에서 strictNullCheck 옵션 키고 시작
<h1 id="title">제목</h1>
let title = document.querySelector('#title');
title.innerHTML = '타이틀';
// typescript에선 error 발생
// title이라는 변수가 null일 수 있기 때문

// 1.
if (title != null) { title.innerHTML = '타이틀'; }	// narrowing 해주면 해결

// 2.
if (title instanceof HTMLElement) { title.innerHTML = '타이틀'; } // 더 좋은 방법

// 3.
let title = document.querySelector('#title') as HTMLElement; // or Element
title.innerHTML = '타이틀'; // 좋은 방법은 아님

// 4.
let title = document.querySelector('#title');
if (title?.innerHTML != undefined) { title.innerHTML = '타이틀'; }
// js 신문법. 왼쪽에 있는 object에 .innerHTML이 존재하면 그거 사용해주고 아니면 undefined 해주라.

// 5. 그냥 strict false 해줘도 된다.​

 

2. 예제2

<a id='link' href='naver.com'></a>
let link = document.querySelector('#link');
if (link instanceof HTMLElement) { link.href = 'https://kakao.com'; } // error
// HTMLElement라는 타입은 href 라는 속성이 없기 때문

let link = document.querySelector('#link');
if (link instanceof HTMLAnchorElement) { link.href = 'https://kakao.com'; } // good

// a : HTMLAnchorElement
// img : HTMLImageElement
// h1~h6 : HTMLHeadingElement ...

 

3. 예제3

let btn = document.querySelector('#btn');
btn.addEventListener('click', function() { console.log('hi'); });
// error - btn이라는 변수는 null일 수 있음

// 정석
let btn = document.querySelector('#btn');
if (btn instanceof HTMLButtonElement) {
	btn.addEventListener('click', function() { console.log('hi'); });
}

// optional chaining (2020년 이후 브라우저들은 사용 가능)
let btn = document.querySelector('#btn');
btn?.addEventListener('click', function() { console.log('hi'); });

 

4. 예제4

<a class='naver' href='naver.com'>link</a>
<a class='naver' href='naver.com'>link</a>
<a class='naver' href='naver.com'>link</a>
let linkArr = document.querySelector('.naver');
if (linkArr.isArray) {	// array check 안해주면 linkArr.length에서 에러
	for (let i = 0; i < linkArr.length; i++) {
        if (linkArr[i] instanceof HTMLAnchorElement) {
            linkArr[i].href = 'https://kakao.com';
        }
    }
}

 

Comments