본문 바로가기
IT/typescript

[Typescript] Type Assertion

by 내일은교양왕 2024. 3. 16.

언제 사용하나

Typescript가 알 수 없는 type이거나 추론한것보다 개발자가 더 정확한 타입을 알고 있을 때 타입을 강제할 수 있다.

 

예) getElementById에서는 HTMLElemnt를 리턴하는데, 개발자는 canvas를 가져올것을 알기에 HTMLCanvasElement 으로 강제시킨다.

const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;

 

특징

컴파일 때 사라지기에 런타임 때 영향을 받지 않는다. 그래서 강제한 타입이 틀리더라도 null이나 exception이 발생되지 않는다. 하지만 조심해야 한다. 경험사례로, string을 enum 타입으로 강제해서 사용했지만 런타임에서는 enum타입에 맞지 않아 undefined로 처리될 수도 있다. 

 

타입 강제는 오직 해당 타입의 위 또는 아래의 타입으로만 변경할 수 있다. 하지만 꼭 필요한 상황에는 타입 강제를 두번하여 원하는 타입으로 강제시킬 수 있다.

const x = 'hello' as number; // doesn't work
const x = 'hello' as any as number // works
console.log(x, typeof x) // hello, string

 

 

 

 

 

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions

 

Documentation - Everyday Types

The language primitives.

www.typescriptlang.org