TypeScript 'is' 를 아세요?

그랴·2025년 2월 22일

TIL

목록 보기
2/4
post-thumbnail

👀 is

User-defined type guard functions
TypeScript 1.6 adds a new way to narrow a variable type inside an if block, in addition to typeof and instanceof. A user-defined type guard functions is one with a return type annotation of the form x is T, where x is a declared parameter in the signature, and T is any type. When a user-defined type guard function is invoked on a variable in an if block, the type of the variable will be narrowed to T.

타입스크립트 1.6에서는 기존의 typeof, instanceof 대신 if 문 내에서 타입을 좁힐 수 있는 새로운 방식을 추가했습니다. 유저 정의 타입 가드 함수는 리턴 타입이 x is T 형식인 함수로, 여기서 x는 함수에서 선언된 매개변수이며 T는 any 타입입니다. if 문 안에서 유저 정의 타입 가드 함수가 실행되면, 변수의 타입은 T로 추론됩니다.


✅ is 키워드를 사용한 타입 체커 함수 예시


읽어 볼 것
1. parameter와 반환 type의 관계
2. 타입 가드의 정확성

profile
낮에는 코드 치고 밤에는 글 씁니다.

0개의 댓글