Narrowing 하는 추가적인 방법

고재현·2023년 8월 10일
0

TypeScript

목록 보기
11/13
post-thumbnail

Narrowing 하는것은 귀찮은데 특히나
1. undefined 타입일 경우 처리
2. 복잡한 object 자료들 narrowing
위 두개가 가장 잦고 귀찮다.

그래서 이번엔 쉽게 narrowing하는 방법을 알아보겠다.

null & undefined 체크

거의 if 문으로 아래처럼 코드를 짤 텐데

if(저 변수가 undefined일 경우) ~~해주세요

&&를 쓰게 되면 저런 if문을 생략할 수 있다.

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

이렇게 하면 되는데 참고로
if(변수!=null) 이렇게 걸어도 null, undefined 두개를 동시에 거를 수 있게 된다.

in 연산자로 narrowing

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

이렇게 서로 다른 유니크한 속성들을 가지고 있다면
in을 써서 narrowing이 가능하다.

instanceof 로 narrowing

Date라는 클래스로부터 생산된 object가 있을 때
instanceof 키워드를 붙여서 부모 클래스가 누군지 검사할 수 있다.

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

literal type이 있다면

type Car = {
  wheel : '4개',
  color : string
}
type Bike = {
  wheel : '2개',
  color : string
}
function 함수(x:Car | Bike){
  if(x.wheel === '4개'){
 	console.log('이 차는 '+ x.color)
  }else {
    console.log('이 바이크는 '+x.color)
  }
}

유사하게 생긴 object타입이 있다면
속성명 in 오브젝트자료 (불가능)
오브젝트 instanceof 부모class(불가능)
이기 때문에 위의 코드처럼
literal type을 사용해서 narrowing을 하면 된다.

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

2개의 댓글

comment-user-thumbnail
2023년 8월 18일

color : string 라는 건 무슨색인가요?

1개의 답글