늘 겸손하게

TypeScript - 타입 가드 본문

Programming/TypeScript

TypeScript - 타입 가드

besforyou999 2023. 11. 2. 15:38

 

 

단언의 문제점

 

단언으로 모든 오류를 해결할 순 없다.

 

function printText(el: Element) {
  console.log(el.textContent)
}

const h1 = document.querySelector('h1')
printText(h1);

 

타입스크립트는 마지막 줄에서 오류를 출력한다. 

 

여기서 단언을 통해 타입스크립트 에러 출력은 막을 수 있지만 실제 코드를 실행해보면 오류가 발생합니다.

function printText(el: Element) {
  console.log(el.textContent)
}

const h1 = document.querySelector('h1') as HTMLHeadingElement
printText(h1);

 

 

위와 같은 문제 해결은 타입 가드를 통해 가능합니다.

 

타입 가드

 

방법 1

 

간단히 if 조건을 추가해 문제를 해결할 수 있습니다.

 

function printText(el: Element) {
  console.log(el.textContent)
}

const h1 = document.querySelector('h1')
if (h1) {
  printText(h1);
}

 

 

방법 2

 

instanceof를 활용합니다.

function printText(el: Element) {
  console.log(el.textContent)
}

const h1 = document.querySelector('h1')
if (h1 instanceof HTMLHeadingElement) {
  printText(h1);
}

 

 

방법 3

 

typeof 를 사용합니다.

// 타입 가드 (Guards)
function concatToStr(a: (number | string), b: (number | string)) {
  let result = 'Result : '
  if (typeof a === 'number') {
    result += a.toString()
  } else {
    result += a.toUpperCase()
  }

  result += ' '

  if (typeof b === 'number') {
    result += b.toString()
  } else {
    result += b.toUpperCase()
  }

  console.log(result)
}

concatToStr(100, "200");