What is Type Narrowing?
Type Guards are expressions that perform runtime checks that allow the TypeScript compiler to narrow a variable to a more specific type within a block of code.
1. The typeof Guard
Use
typeof to distinguish between primitive types like strings, numbers, and booleans.typescript
2. The instanceof Guard
Use
instanceof to check if an object is an instance of a specific class.typescript
3. User-Defined Type Guards
Wait! Sometimes built-in guards aren't enough. you can create your own guard using a function with a Type Predicate (
x is T) as the return type.typescript
4. The in Operator Guard
The
in operator checks if a property exists on an object.typescript
Summary
| Guard | Usage | Best For... |
|---|---|---|
| typeof | typeof x === "s" | Primitives (string, number, etc.) |
| instanceof | x instanceof C | Classes and Objects |
| is T | fn(x): x is T | Custom complex logic |
| in | "prop" in x | Checking for property existence |
| Equality | x === "value" | Literal types |
| Truthy | if (x) { ... } | Filtering out null or undefined |
| Logic | Narrowing turns "General" types into "Specific" ones | |
| Safety | Prevents "Property does not exist" errors at compile-time | |
| Modern | Powering complex unions and intersection logic | |
| Discriminated | x.kind === "circle" (The most powerful pattern!) | |
| Refactor | Replacing as Type with Type Guards for better safety | |
| Consistency | Ensuring code behaves as expected across all types |