TS로 HTML 변경&조작시 주의점

고재현·2023년 8월 8일
0

TypeScript

목록 보기
8/13
post-thumbnail

자바스크립트의 존재의 이유는 당연하게 html을 잘 조작하기 위해서이다.
타입스크립트를 통한 html 조작도 당연히 가능하지만, 자바스크립트를 쓸 때보다 귀찮다는 단점이 있다.

1. stricNullCheck

tsconfig.json파일을 열어서

{
    "compilerOptions": {
        "target": "ES5",
        "module": "commonjs",
        "strictNullChecks": true
    }
} 

strickNullChecks옵션을 true로 바꾸자.
그래야 변수 조작하기 전에 이게 null인지 아닌지 확인 가능하다.

2. HTML 파일 준비

<h4 id="title">안녕하세요</h4>
<a href = "naver.com">링크</a>
<button id="button">버튼</button>

<script src="변환된 파일.js"></script>
  • 자바스크립트라면
let 제목 = document.querySelector('#title');
제목.innerHTML = '반갑다'

이렇게하면 안녕하세요가 반갑다로 바뀐다.
하지만 ts에서는 오류를 내준다.

몇가지 해결책을 알아보자.

제목 바꾸는 방법들

1. narrowing
let 제목 = document.querySelector('#title');
if(제목 != null){
  제목.innerHTML = '반갑다'
}
2. instanceof

instanceof도 narrowing의 한 종류인데 뒤에 더 자세하게 알려주도록 하겠다.

let 제목 = document.querySelector('#title');
if(제목 instanceof HTMLElement){
	제목.innerHTML = '반갑다'
}
3. assertion
let 제목 = document.querySelector('#title') as HTMLElement;
제목.innerHTML = '반갑다'
4. optional chaining
let 제목 = document.querySelector('#title');
if(제목?.innerHTML != undefined){
   제목.innerHTML = '반갑다'
   }

링크 바꿔보기

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

어라? 왜 에러가 뜨지?

  • html 태그 종류별 정확한 타입명칭

    a -> HTMLAnchorElement
    img -> HTMLImageElement
    h4 -> HTMLHeadingElement
    ...

이렇게 정확한 타입으로 narroing 해줘야 잘 된다

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

이러면 에러 없이 잘 작동된다.

이벤트리스너 부착

let 버튼 = document.getElementById('button');
버튼.addEventListener('click',function(){
  console.log('안녕')
})

이 또한 narrowing을 하지 않아서 에러가 뜰 것이다.
하지만 narrowing을 하지 않고 에러를 잡는 방법이 있는데

let 버튼 = document.getElementById('button');
버튼?.addEventListener('click',function(){
  console.log('안녕')
})

이렇게 object?.어쩌고 를 해주는 것이다.
?가 바로 optional chaining 문법이다.

대략 설명해주면
어쩌고라는 자료가 object에 존재하면 그걸 뽑아주고
없다면 undefined로 남겨달라~ 라는 뜻이다.

profile
잘못된 내용이 있다면 알려주세요..!

0개의 댓글