TypeScript(11)

조은형·2023년 10월 20일

in 연산자로 object narrowing

type Fish = { swim: string };
type Bird = { fly: string };
function 함수(animal: Fish | Bird) {
  if ("swim" in animal) {
    return animal.swim
  }
  return animal.fly
} 

이런 코드가 있을 때 typeof이런 것을 사용하는 것이 아닌 특정 값이 있는지로 narrowing을 할 수 있다.

let 날짜 = new Date();
if (날짜 instanceof Date){
  console.log('참이에요')
}

만약 class로부터 생성된 object 인스턴스라면 instanceof를 사용해도 된다.

type Car = {
  wheel : '4개',
  color : string
}
type Bike = {
  wheel : '2개',
  color : string
}

function 함수(x : Car | Bike){
  if (x.wheel === '4개'){
    console.log('the car is ' + x.color)
  } else {
    console.log('the bike is ' + x.color)
  }
}

이렇게 코드가 같고 내용만 좀 다르다면 바퀴의 개수로 구분 짓는 것도 좋은 방법일 것이다.

profile
좋은 형

0개의 댓글