What are type guards in TypeScript
· Category: TypeScript
Short answer
Type guards are expressions that narrow the type of a variable within a conditional block, allowing safe access to type-specific members.
Steps
- Use
typeoffor primitives:if (typeof value === 'string') { ... } - Use
instanceoffor classes:if (error instanceof HttpError) { ... } - Use
infor object properties:if ('id' in obj) { ... } - Write custom type predicate functions:
function isString(x: unknown): x is string { ... } - Use discriminated unions with a shared literal property for exhaustive checks.
Tips
- Custom type predicates are powerful for API response validation and domain modeling.
- Combine type guards with early returns to flatten nested conditionals.
Common issues
instanceofchecks fail across realms like iframes or VM contexts.- Type guards only narrow within the scope where the condition is true; reassignment can invalidate the narrowed type.