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
에서는 character
에 fireBall()
이 없기 때문에 컴파일 에러가 나지만 battle2
에서는 character
를 Wizard
로 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을 한 값이 어떤 타입을 가져야 하는지 타입 확인(힌트) 용도로 알려주는거임.
<>
으로 type assertion을 할 수 있음.
<targetType> value
React같은 일부 라이브러리에서는 <>
을 사용할 수 없음. 따라서 type assertion을
let netPrice = <number>getNetPrice(100, 0.05, false);
- type aseertions은 컴파일러 한테 값을 특정 타입으로 다루라고 알려줌
- type assertion은 타입을 바꿔주지 않음
- type assertion은 'as
키워드가
<>`문을 사용해서 할 수 있음.