TypeScript

타입스크립트로 HTML 변경과 조작할 때 주의점들

단점이없어지고싶은개발자 2022. 5. 12. 22:34
반응형
const title = document.getElementById('title');

//HTML 조작시 narrowing 방법 5개 정도가 있다.
if (title !== null) {
  title.innerHTML = 'hello';
}

if (title instanceof Element) {
  //Element 요소의 타입이냐라는 뜻
  title.innerHTML = 'instanceof';
}

//const title = document.getElementById('title') as Element;
//무조건 이걸로 Element로 바꿔서 가능. 비상시 사용.

if (title?.innerHTML) {
  //title이 있냐 없냐를 간단히 요약한 문법, optional chaining
  title.innerHTML = '?. 이냐 아니냐';
}

const link = document.querySelector('.link');

if (link instanceof HTMLAnchorElement) {
  //타입스크립트가 제공하는 기본타입이나 Element타입들을 구체적으로 넣어줘야 한다.
  link.href = 'google.com';
}

const button = document.querySelector('#button');

//button 예시
button?.addEventListener('click', () => {
  console.log('click');
});

//image 예시
const img = document.querySelector('#image');

if (img instanceof HTMLImageElement) {
  img.src = 'new.jpg';
}
반응형