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

Equality Narrowing: `===` 와 `==`

~8 min · narrowing, equality, discriminated-unions

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"x === 'literal' 이 compiler 가 너의 discriminated union 이 옳게 연결됐는지 검증하는 법."

Narrowing 연산으로서 equality

값을 literal 과 비교가 narrow. if (x === 'red') 분기 안에서 compiler 가 x 가 literal 타입 'red' 인 거 알아. x 가 이전엔 'red' | 'blue' | 'green' 이었으면, 이제 그냥 'red'. else 분기에선 'blue' | 'green'.

이게 discriminated union 이 switch 와 chained if 문에서 작동하게 만드는 operator. if (shape.kind === 'circle') 가 전체 shape object 를 circle variant 로 narrow.

Loose equality (==) — 거의 절대 안 써

JavaScript 의 == 가 타입 coercion 수행: '1' == 1true. TypeScript 가 == 를 narrowing operator 로 다루지만, narrowing 이 coercion 규칙 따라 — 혼란스럽고 거의 원하는 거 아냐.

규칙: narrowing 엔 항상 === 써. == 는 명시적 null/undefined 체크 (x == nullnull AND undefined 둘 다 match — 문맥에 명확한 의도된 idiom) 에만 예약. 그 외엔 strict equality.

as const 의 상수와 함께 === narrowing

as const 와 equality narrowing 결합이 매우 흔한 패턴. const STATUSES = ['idle', 'loading', 'done'] as const 가 literal 타입 줘. 그다음 어떤 x === STATUSES[0] 이든 x'idle' 로 옳게 narrow.

Strict equality 가 tagged union 의 narrowing 일꾼. Strict 유지; literal 타입 의지; compiler 의 inference 신뢰.

Code

Strict equality 와 정당한 `==` 사용 하나·typescript
type Status = 'idle' | 'loading' | 'done' | 'error';

function handle(s: Status): string {
  if (s === 'idle') {
    return 'waiting';           // s: 'idle'
  }
  if (s === 'loading') {
    return 'spinner';           // s: 'loading'
  }
  // 여기서 s 가 'done' | 'error' 로 narrow
  if (s === 'done') {
    return 'check';             // s: 'done'
  }
  return 'cross';               // s: 'error' — 제거로
}

// == null 이 null 과 undefined 둘 다 잡아.
function defaultName(name: string | null | undefined): string {
  if (name == null) {           // null OR undefined match
    return 'anonymous';
  }
  return name;                  // name: string
}

External links

Exercise

Status 가 4개 값의 literal union 인 priority(status: Status): number 함수 써. Chained equality narrowing 써서 각각에 다른 숫자 assign. switch 쓰지 마 — if 체인만. Compiler 가 체인 통해 옳게 narrow 하는지 확인.
Hint
if (s === '...') return 후 compiler 가 그 variant 를 s 의 타입에서 제거. 마지막 분기 시점엔 한 variant 만 남아 — compiler 가 어느 거인지 알아.

Progress

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

댓글 0

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

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