Type Assertions

kukudas·2022년 2월 9일
0

TypeScript

목록 보기
29/39

Introduction to Type Assertions in TypeScript

type assertion은 타입스크립트 컴파일러한테 해당 타입으로 가정하도록 지시함. as키워드를 사용해서 할 수있음.

expression as targetType

type assertion은 type narrowing으로 알려져있기도함. type assertion으로 유니온 타입을 narrow 할 수 있음.

function getNetPrice(price: number, discount: number, format: boolean): number | string {
    let netPrice = price * (1 - discount);
    return format ? `$${netPrice}` : netPrice;
}

위 함수는 price, account, format을 인자로 받아서 유니온 타입인 number | string을 리턴해줌.
만약에 format이 true라면 함수는 가격을 string으로 리턴해주고 false면 number로 리턴해줌.

let netPrice = getNetPrice(100, 0.05, true) as string;
console.log(netPrice);

// Output:
$95

위 코드는 as 키워드를 사용해서 컴파일러한테 netPrice에 할당된 값이 string이라고 알려줌.
비슷하게 아래는 getNetPrice()가 리턴한 값이 number라고 알려줌.

let netPrice = getNetPrice(100, 0.05, false) as number;
console.log(netPrice);

// Output:
95

아래 코드를 보면 battle1에서는 characterfireBall()이 없기 때문에 컴파일 에러가 나지만 battle2에서는 characterWizard로 type assertion 했기 때문에 컴파일 에러가 나오지 않음.

class Character {
    hp: number;
    isWizard(): boolean {
        return true;
    }
}
class Wizard extends Character {
    fireBall() {
    }
}

function battle1(character: Character) {
    if (character.isWizard()) {
        character.fireBall(); // Property 'fireBall' does not exist on type 'Character'.
    }
}
function battle2(character: Character) {
    if (character.isWizard()) {
        (character as Wizard).fireBall(); // Pass
    }
}

주의할 점은 type assertion은 타입 캐스팅을 하지 않고 컴파일러에게 type assertion을 한 값이 어떤 타입을 가져야 하는지 타입 확인(힌트) 용도로 알려주는거임.

The alternative Type Assertion syntax

<>으로 type assertion을 할 수 있음.

<targetType> value

React같은 일부 라이브러리에서는 <>을 사용할 수 없음. 따라서 type assertion을

let netPrice = <number>getNetPrice(100, 0.05, false);

Summary

  • type aseertions은 컴파일러 한테 값을 특정 타입으로 다루라고 알려줌
  • type assertion은 타입을 바꿔주지 않음
  • type assertion은 'as키워드가<>`문을 사용해서 할 수 있음.

출처1
출처2

0개의 댓글

관련 채용 정보