Type System Deep Dive
Type Guards — typeof, instanceof, in, custom type predicates
Master TypeScript type guards using typeof, instanceof, in operator, and custom user-defined type predicates (arg is Type).
A Type Guard is a runtime expression or function that performs a check on a variable to guarantee its specific type to the TypeScript compiler within a conditional block.
1. The typeof Type Guard
Use typeof to narrow primitive types (string, number, boolean, symbol, bigint, undefined, function).
2. The instanceof Type Guard
Use instanceof to narrow values created by class constructor functions or built-in classes (Date, RegExp, HTMLInputElement, custom classes).
3. The in Operator Type Guard
Use the in operator to check if a specific property name exists on an un-narrowed object union:
4. Custom User-Defined Type Predicates (arg is Type)
To create reusable type guard helper functions, define a return type using a Type Predicate: paramName is TargetType.
5. Interactive Code Playground
Test type guards below:
6. Summary Comparison Table
| Type Guard | Target Types | Example Syntax |
|---|---|---|
typeof | Primitives | if (typeof x === "string") |
instanceof | Class instances & built-ins | if (x instanceof Date) |
in | Property presence in objects | if ("swim" in animal) |
is) | Complex domain structures | function isUser(x: any): x is User |