본문 바로가기
Frontend/TypeScript(완)

[TS] TS연습하기7

by VictorMeredith 2023. 4. 12.

//Narrowing 할 수 있는 방법 더 알아보기
const 언디파인드찾기 = (a:string|undefined):void=>{ //null 타입도 찾아준다.
  if(a && typeof a === 'string'){ //&& 사용하기 : 
    // string 이면 할거
  }
  else{
    // undefined 이면 할거
  }
}


//in 키워드 : 속성명이 다를 경우 사용 가능하다. (Object Narrowing)
type Fish = {swim : string}
type Bird = {fly :string}

const 애니멀 = (animal :Fish|Bird):void=>{ 
  if('swim' in animal){ //Fish 타입 검사
    //swim 이라는 속성이 들어있으면 할거
  }
  else{
    //이외에 할거
  }
}


// instanceof 를 사용한 Narrowing (오브젝트 instanceof 부모class)
let 날짜 = new Date();
if(날짜 instanceof Date){
  //어쩌구
}


//비슷한 object 타입일 경우 literal type 강제로 만들어두면 도움이 된다. (고정값)
//애초에 비슷한 타입인 경우 하나로 만들어도 된다.
type Car = {wheel: '4개', color:string} 
type Bike = {wheel: '2개', color:string}

const 타입검사 = (a:Car|Bike):void=>{
  if(a.wheel === '4개'){
    //4개일 경우
  }
  else if(a.wheel === '2개'){
    //2개일 경우
  }
  else{
    return
  }
}

//결론 : 논리적으로 타입을 특정지을 수 있다면 narrowing으로 인정해준다.

'Frontend > TypeScript(완)' 카테고리의 다른 글

[TS] TS연습하기9 (public, private, protected, static)  (0) 2023.04.12
[TS] TS연습하기8  (0) 2023.04.12
[TS] TS연습하기6  (0) 2023.04.12
[TS] TS연습하기5  (0) 2023.04.12
[TS] TS연습하기4  (0) 2023.04.12

댓글