[TypeScript] as

최승원·2022년 2월 17일
1

TIL (Today I Learned)

목록 보기
11/21

Type Assertion(타입 단언)

Type Assertion은 내가 TypeScript보다 어떤 값의 타입을 보다 명확하게 알고 있을 때 활용한다.
예를 들어 코드상에서 document.getElementById가 사용되는 경우, TypeScript는 이때 HTMLElement 중에 "무언가"가 반환된다는 것만을 알 수 있는 반면에, 나는 언제나 HTMLCanvasElement가 반환된다는 사실을 이미 알고 있을 수도 있다.

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

이런 경우, 위와 같이 Type Assertion을 활용하면 보다 구체적으로 명시할 수 있다.
Type Assertion은 컴파일러에 의하여 제거되며 코드의 런타임 동작에는 영향을 주지 않는다.

const x = "hello" as number;

// Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

TypeScript에서는 보다 구체적인 또는 덜 구체적인 버전의 타입으로 변환하는 타입 단언만이 허용된다. 이러한 규칙은 위와 같은 “불가능한” 강제 변환을 방지한다.

declare const expr: any;
type T = { a: 1; b: 2; c: 3 };
// ---중간 생략---
const a = (expr as any) as T;

이 규칙은 때로는 지나치게 보수적으로 작용한다. 이런 경우, any(또는 unknown)로 우선 변환한 뒤, 그다음 원하는 타입으로 변환하면 된다.

참조

TypeScript: Documentation - Everyday Types

profile
문의 사항은 메일로 부탁드립니다🙇‍♀️

0개의 댓글