"typeof, instanceof, `in` 으로 안 될 때 자기 narrowing 함수 써."
Type predicate 의 형태
Type predicate 가 arg is T return type annotation 가진 함수. Signature 가 function isUser(x: unknown): x is User 처럼 보임. 함수 body 가 평소대로 boolean 반환. 마법은 return type 에: 함수가 true 반환하면, caller 가 `arg` 가 `T` 타입인 거 배워.
Caller 관점에서 predicate 호출은 typeof 나 instanceof 체크 같아 — 값이 true 분기 안에서 narrow.
안에 뭐 들어가
Predicate 의 body 가 runtime 에 돌아. 타입 검증에 필요한 어떤 체크든 함: property 존재, 값 타입, 구조 매칭, 심지어 다른 predicate 호출. Compiler 가 predicate 신뢰 — true 반환하면 narrowing 발생. (즉 버그 있는 predicate 가 compiler 한테 거짓말; body 신중히 구조화.)
외부 source (JSON, 사용자 입력, 3rd-party API) 에서 온 unknown 입력엔, predicate 가 너의 validation. Zod, Valibot, io-ts 같은 tool 이 이 패턴을 타입-안전 predicate 만드는 parser-generator 로 감싸.
자기 거 쓸 때
- 타입 안 붙은 데이터 validating (parse 된 JSON, dynamic fetch).
- 깨끗한 discriminator 없는 union 의 object 모양 체크.
- 단일 typeof/instanceof 에 너무 복잡한 체크 감싸기.
Compiler 가 너의 predicate 신뢰. Predicate 가 실제로 `T` match 안 하는 object 에 true 반환하면, type system 이 이제 거짓말. JSON parser 와 같은 주의로 predicate 써 — 안 안전 입력과 안전 코드 사이의 경계.