intermediate
Narrowing and type guards
Use control flow, predicates, assertion functions, typeof, in, instanceof, and custom validation.
Narrowing refines a broad type through control flow. `typeof`, `instanceof`, `in`, equality checks, custom type predicates, and assertion functions help the compiler understand what is safe. Runtime validation is still required at trust boundaries.
function isUser(value: unknown): value is User {
return typeof value === 'object' && value !== null &&
'id' in value && typeof (value as User).id === 'string';
}
Start external data as `unknown`, not `any`. A dishonest type predicate can lie to the compiler. Checking only `typeof value === 'object'` is not enough for nested API payloads.
On interviews: explain with a concrete example and name what interviewers probe in production code.
Common pitfalls: mixing similar APIs and forgetting edge cases during live coding.
The trade-off is often clarity versus safety or expressiveness versus maintainability. Checklist:
- Start external data as unknown.
- Keep predicates honest.
- Validate nested shapes.