[TypeScript] 타입스크립트 타입 확정하기 (Narrowing & Assertion)

applejin·2022년 9월 29일
2

TypeScript

목록 보기
2/2
post-thumbnail

Operator '+' cannot be applied to types 'string | number' and 'number' 해결 방법
-> Narrowing / Assertion

1. Narrowing

함수에서 Type이 아직 하나로 확정되지 않았을 경우 사용한다.

if문으로 Narrowing 하기

function 함수(x: number | string){
    if (typeof x === 'string'){
        return x + '1';
    } else {
        return x + 1;
    }
}

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
    }
  • 배타적인 속성이 없을 때

    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);
        }
    }

2. Assertion

변수명 as string
  • as 키워드는 union type 같은 복잡한 타입을 하나의 정확한 타입으로 줄이는 역할
    -> 기존 number 타입을 as string 하면 에러남

  • 타입 쉴드 임시 해제용
    -> return (x as number) + 1 결과를 number 타입처럼 계산해주지 않는다.
    (as는 그냥 주장만 하는거지 실제로 타입을 바꿔주는건 아니기 때문)


👉🏽 참고

  • 코딩애플 온라인 '빠르게 마스터하는 타입스크립트'
profile
front-end developer

0개의 댓글