Safely Working with Multiple Types
Learn how type narrowing works in TypeScript to safely handle union types. This module explains using typeof checks, the in operator, and instanceof checks with real-world examples.
1. Using typeof
The typeof operator is used to narrow primitive types such as string, number, and boolean at runtime.
Basic Example
TypeScript understands the type inside each conditional block and allows only valid operations.
Common Use Case
The typeof operator is commonly used when handling input from forms or APIs.
2. Using the in Operator
The in operator is used to check if a property exists on an object. It helps narrow types when working with object unions.
Basic Example
The presence of the property narrows the type automatically.
Real-World Example
3. Instanceof Checks
The instanceof operator is used to check whether an object is an instance of a specific class.
Basic Example
Real-World Example
Conclusion
Type narrowing is a powerful feature in TypeScript that ensures safe access to properties and methods when working with union types. Using typeof, the in operator, and instanceof checks helps write reliable, maintainable, and error-free code in real-world applications.