Type Guards
Type guards are functions that perform runtime checks and narrow TypeScript types using type predicates.Primitive Type Guards
Check for primitive JavaScript types.Type Signatures
Object Type Guards
Check for various object types and structures.- isArray
- isObject
- isPlainObject
- isObjectAndNotArray
Collection Type Guards
Check for collection types like Map, Set, and FormData.Function Type Guards
Check for function types including async functions.- isFunction
- isAsyncFunction
Browser & Web API Guards
Check for browser-specific types.JSON & Serialization Guards
Check for JSON-serializable values and valid JSON strings.- isValidJsonString
- isJSONSerializable
- isSerializableObject
Advanced Guards
isIterable
Checks if an object is iterable.hasObjectPrototype
Checks if a value has Object.prototype.Assertions
Assertion functions throw errors when conditions aren’t met and narrow types.assert
General-purpose assertion function with overloads.- Boolean Conditions
- Non-Null Values
- Custom Messages
Type Signature
assertDefined
Asserts that a value is not null or undefined.Type Signature
assertENV
Asserts that an environment variable is defined.Type Signature
AssertionError
Custom error class thrown by assertion functions.Class Definition
Practical Examples
API Response Validation
Form Data Processing
Configuration Loading
Type Narrowing with Guards
Best Practices
Choose the Right Guard
Choose the Right Guard
- Use
isObjectfor general object checks (includes arrays, Maps, etc.) - Use
isPlainObjectfor plain JavaScript objects only - Use
isObjectAndNotArraywhen you specifically need to exclude arrays - Use
isValidJsonStringfor validating JSON strings before parsing
Assertion Error Messages
Assertion Error Messages
- Always provide descriptive error messages
- Include context about what failed and why
- Use
assertENVspecifically for environment variables - Catch
AssertionErrorspecifically when needed
Type Narrowing
Type Narrowing
- Guards narrow types automatically with type predicates
- Use assertions at function boundaries (e.g., API responses)
- Combine multiple guards for complex validation
- Prefer guards over type assertions (
as) for runtime safety
Performance Considerations
Performance Considerations
- Guards are runtime checks - use judiciously in hot paths
isPlainObjectis more expensive thanisObject- Consider caching validation results for repeated checks
- Use TypeScript’s compile-time types when possible
See Also
Type Utilities
Type transformation utilities
Enums
Type-safe enum utilities