Type Guards
A type guard is a boolean expression that does a runtime check to guarantee the type in a certain scope.
Built-in Type Guards
typeof
- checks for primitive typesin
- Checks for object propertiesinstanceof
- checks for class instances
Type Guard with typeof
A typeof
type guard can protect primitive types.
1 |
|
When dealing with complex types, a typeof
type guard may not be very useful since the type of a complex type will always be "object"
(see here). In such cases, an in
type guard would be more effective.
Type Guard with in
1 |
|
While the in
type guard is effective for checking plain objects, it is recommended to use the instanceof
type guard when checking a class
.
Type Guard with instanceof
1 |
|
Custom Type Guard
1 |
|
Type Predicates
A type predicate is a syntax construct used to define the return type of a type guard. It allows the type guard to assert a specific type to its input. Here is an example of a type predicate: error is AxiosError