TypeScript - typeof Type Operator

CH_Hwang·2022년 2월 24일
0

TypeScript

목록 보기
4/12

typeof

자바스크립트에서 이미 있는 typeof.
타입스크립트에서는 이 typeof를 type context에서 사용 할 수 있다.

let s = "hello";
let n: typeof s; // let n: string;

기본타입에서는 유용하진 않지만 다른 type operators와 같이 사용하면 많은 패턴들을 간편하게 쓸 수 있다.

function f(){
  return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>; // type P = { x: number; y: number;}

제한사항

타입스크립트는 의도적으로 typeof를 적용시킬 수 있는 표현들을 제한함.
typeof는 식별자나 그들의 프로퍼티에만 적용 가능하다.

// Meant to use = ReturnType<typeof msgbox>
let shouldContinue: typeof msgbox("Are you sure you want to continue?");
',' expected.

0개의 댓글