Narrowing 방법

김범주·2022년 7월 14일
0

typescript

목록 보기
10/23
post-thumbnail

&&

1 && null && 3   // null이 남음
undefined && '안녕' && 100  // undefined 남음

&& 기호로 비교할 때 true와 false를 넣는게 아니라 자료형을 넣으면
&& 사이에서 처음 등장하는 falsy 값을 찾아주고 그게 아니면 마지막 값을 남겨준다.

사용예시

function printAll(strs: string | undefined) {
  if (strs && typeof strs === "string") {  
    console.log(s);
  } 
}

이렇게 사용하면 변수가 undefined라면 if문이 실행되지 않고 변수가 string타입이면 if문이 실행됨.

변수가 null, undefined인 경우를 쉽게 거를 수 있는 문법

in

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

이런 식으로 유니크한 속성을 가지고 있다면 그 속성을 가지고 narrowing이 가능

literal type

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

function 함수(x : Car | Bike){
  if (x가 Car타입이면요){
    console.log('이 차는 ' + x.color)
  } else {
    console.log('이 바이크는 ' + x.color)
  }
}

각 타입에 유니크한 literal type을 지정해두고 그걸로 narrowing.

typeof를 사용하기 힘든 경우일 때!

profile
개발꿈나무

0개의 댓글