C.W.K.
Stream
Lesson 01 of 05 · published

`typeof` Narrowing

~8 min · narrowing, typeof, primitives

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"가장 기본적인 narrowing tool. 모든 primitive 에 작동, 어디서나 켜져."

Value-level `typeof`

Foundations 트랙에서 회상: `typeof` 가 2 의미. Value-level `typeof` 가 runtime 에 돌고 7개 문자열 중 하나 반환: 'string', 'number', 'boolean', 'undefined', 'object', 'function', 'symbol', 'bigint'. (`null` 세면 8개 — 근데 typeof null === 'object', 유명한 JavaScript quirk.)

TypeScript 가 이 문자열 정확한 집합을 narrowing 연산으로 이해. if (typeof x === 'string') 그 분기 안에서 `x` 를 `string` 으로 narrow. 분기 밖에선 union 에서 `string` 뺀 거.

`typeof` 가 narrow 할 수 있는 거

7개 primitive 타입: `string`, `number`, `boolean`, `undefined`, `object`, `function`, `symbol`, `bigint`. 그게 전체 집합. 더 구체적인 거 (특정 object 모양, class instance, literal) 는 다른 narrowing tool 필요 — typeof 는 primitive layer 까지만 봐.

`typeof === 'object'` 함정

typeof null === 'object' 가 `true` 반환. 1995년 JavaScript 버그가 기능 됐어. `typeof x === 'object'` 로 narrow 하고 union 에 `null` 포함되면, 분기 안에 여전히 `null` 있어.

Fix: 명시 null 체크 추가. if (typeof x === 'object' && x !== null). TypeScript 가 narrowing 에 내장 — null 체크 후 `x` 가 non-null object 타입만이라는 거 알아.

typeof 는 primitive 용. Object, class, 모양 체크엔 `instanceof`, `in`, type predicate 써. 체크하는 타입에 옳은 tool 손 뻗어.

Code

typeof — 옳은 case 와 null 함정·typescript
// Primitive 용 typeof narrowing.
function toUpper(x: string | number): string {
  if (typeof x === 'string') {
    return x.toUpperCase();        // x: string
  }
  return x.toFixed(2);             // x: number
}

// null 함정.
function unsafe(x: { name: string } | null): string {
  if (typeof x === 'object') {
    // x: { name: string } | null  — null 이 여전히 여기!
    return x.name;                 // ❌ Object is possibly 'null'
  }
  return '';
}

function safe(x: { name: string } | null): string {
  if (typeof x === 'object' && x !== null) {
    return x.name;                 // ✅ { name: string } 로 narrow
  }
  return '';
}

External links

Exercise

'a string', 'a number', 또는 'nothing' 반환하는 describe(x: string | number | null) 함수 써. typeof 와 명시적 null 체크 써. 어느 분기에도 compiler 불평 안 하는지 확인 — 그리고 각 x hover 해서 모든 줄에서 타입이 기대한 거인지 확인.
Hint
null 체크가 먼저 와야 하거나 typeof === 'object' && x !== null 과 함께. typeof === 'string' 과 typeof === 'number' 각각 명백한 방식으로 narrow. 순서보다 명시성이 더 중요.

Progress

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

댓글 0

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

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