Discover how a simple function can make your code smarter and safer by telling TypeScript exactly what it's working with!
Why Type predicates in practice in Typescript? - Purpose & Use Cases
Imagine you have a list of different shapes, like circles and squares, and you want to find out which ones are circles by checking their properties manually.
Manually checking each shape's properties every time is slow and easy to mess up. You might forget a check or mix up types, causing bugs that are hard to find.
Type predicates let you create clear, reusable checks that tell TypeScript exactly what type an object is. This helps catch mistakes early and makes your code easier to read and maintain.
function isCircle(shape: any) { return shape.radius !== undefined; }
if (isCircle(shape)) { console.log(shape.radius); }function isCircle(shape: unknown): shape is Circle { return (shape as Circle).radius !== undefined; }
if (isCircle(shape)) { console.log(shape.radius); }It enables safer and clearer code by letting TypeScript know the exact type after a check, reducing errors and improving developer confidence.
When building a drawing app, you can use type predicates to safely handle different shapes and their unique properties without risking runtime errors.
Manual type checks are error-prone and repetitive.
Type predicates provide a clear way to tell TypeScript about types after checks.
This leads to safer, cleaner, and more maintainable code.