[TS] union 타입과 narrowing

2021. 12. 27. 17:29카테고리 없음

 

narrowing

to make something less wide

 

여라가지 타입이 모인 union타입의 경우를 파라미터값으로 사용시 narrowing을 사용하여

각 타입마다 조건을 걸어주어야한다.

 

if(typeof x ==="string")

파라미터 x 가 string일경우 string일떄 실행할 내용

 

디버깅용 비상용

assertion

type to type   (X)

types to type (O)

union같이 여러가지 타입이 있는것을 한가지로 특정할때..!

x as string; 이런식으로 쓰는데 

 

narrowing해서 if문 쓰는게 정석임 

assertion 버그추적 힘듬 = 타입스크립트의 취지와 역행함