C.W.K.
Stream
Lesson 02 of 06 · published

`typeof` (타입-레벨): Value-to-Type 다리

~8 min · type-manipulation, typeof, type-from-value

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"값 썼어. 이제 그 타입 무료로 가져."

타입-레벨 `typeof`

타입 위치에서 typeof someValue 가 `someValue` 의 타입으로 평가. const u = { id: 1, name: 'Pippa' }; type U = typeof u — `U` 가 `{ id: number; name: string }`. Compiler 가 값의 추론 타입 읽고 그 모양의 타입 줘.

이건 runtime `typeof` operator (runtime 에 문자열 반환) 와 별개. 타입-레벨 버전은 타입 위치에만 존재, 타입과 값 sync 유지하는 TypeScript 의 가장 유용한 기능 중 하나.

손 뻗을 때

상수 → 타입. 상수 있고 같은 모양을 타입으로 표현하고 싶으면, `typeof constant` 가 re-type 없이 해. const ROUTES = { CHAT: '/chat' } as const; type Routes = typeof ROUTES.

함수 → signature. `ReturnType` 과 `Parameters` 와 결합, 이름 붙이지 않고 함수 조각 추출 가능. type Result = ReturnType<typeof fetchUser>.

External library. Library 가 값 export 하지만 타입은 안 export 하면, `typeof exportedValue` 가 타입 회복.

타입-레벨 `typeof` 가 값을 진실 source 로, 타입을 derived view 로 만드는 법. 값이 도는 거; 타입이 compiler 가 체크하는 거. 둘 다 한 선언에서.

Code

typeof 통한 값 → 타입·typescript
// 상수에서 타입.
const defaultUser = {
  id: 0,
  name: 'anon',
  permissions: [] as string[],
};

type User = typeof defaultUser;
// { id: number; name: string; permissions: string[] }

// 함수에서 signature.
function fetchPost(id: number): Promise<{ title: string; body: string }> {
  return Promise.resolve({ title: '', body: '' });
}

type FetchPostFn = typeof fetchPost;
// (id: number) => Promise<{ title: string; body: string }>

type FetchPostReturn = ReturnType<typeof fetchPost>;
// Promise<{ title: string; body: string }>

// External library.
import { someConfig } from 'their-library';
type TheirConfig = typeof someConfig;     // 타입 export 안 할 때 회복

External links

Exercise

어딘가에 쓴 복잡한 config object 가져와. typeof config 로 타입 derive 하고 type system 이 손으로 쓸 같은 모양 보는지 확인. 그다음 config 에 as const 추가 — derived 타입에서 뭐 바뀌어?
Hint
as const 없으면 primitive widening (string 필드가 string 됨). 있으면 literal 보존 (string 필드가 특정 literal 타입 됨). 타입이 이제 값과 정확히 match.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.