What are Type Predicates in TypeScript?
October 29, 2023
What's a Type Predicate?
A type predicate is a function whose return type is a boolean value that's used to narrow down types. They come handy when TypeScript can't automatically infer the type of a variable or when more sophisticated type checks are needed.
The syntax for a type predicate function is:
arg is Type syntax is the actual type predicate. It's signaling to TypeScript that, when the function returns
true, the caller can be certain that
arg is of type
Why Are They Useful?
Consider scenarios where you have a union type (e.g.,
string | number) and you want to run different code based on the type. The standard way is to use type guards:
instanceof are useful, they don't cover all cases. Enter type predicates. They allow developers to create custom type guards that narrow types based on bespoke logic.
Examples of Using Type Predicates
1. With Interfaces
Imagine you have two interfaces,
Dog, and you want to check if an animal is a
Now, whenever you use
isCat in a conditional, TypeScript knows the type:
2. With Classes
Similarly, you can use type predicates with classes:
- Ensure Accuracy: The logic inside your type predicate must be accurate. If the logic claims an instance is of a specific type when it's not, it could lead to runtime errors.
- TypeScript's Trust: Once the type predicate function returns
true, TypeScript completely trusts that the type is narrowed. It doesn't double-check, so make sure your predicates are correct.
- No Direct Output: The main aim of type predicates isn't to return a boolean for the developer to use, but rather to provide type information to TypeScript. They're primarily for type checking and not for runtime checks.
- A type predicate is a function that narrows types based on its return value.
- The syntax for a type predicate is
arg is Type.
- They're especially useful when working with union types or when
- Always ensure that the logic in the type predicate function is accurate to avoid potential runtime errors.
How to Truncate Date in MySQL