Chapter 5. Conditional Types

In this chapter, we will take a good look at a feature that is unique to TypeScript: conditional types. Conditional types allow us to select types based on subtype checks, allowing us to move around in the type space and get even more flexibility in how we want to design interfaces and function signatures.

Conditional types are a powerful tool that allows you to make up types on the fly. It makes TypeScript’s type system turing complete, as shown in this GitHub issue, which is both outstanding but also a bit frightening. With so much power in your hands, it’s easy to lose focus on which types you actually need, leading you into dead ends or crafting types that are too hard to read. Throughout this book, we will discuss the usage of conditional types thoroughly, always reassessing that what we do actually leads to our desired goal.

Note that this chapter is much shorter than others. This is not because there’s not a lot to say about conditional types: quite the contrary. It’s more because we will see good use of conditional types in the subsequent chapters. Here, we want to focus on the fundamentals and establish terminology that you can use and refer to whenever you need some type magic.

5.1 Managing Complex Function Signatures

Problem

You are creating a function with varying parameters and return types. Managing all variations using function overloads gets increasingly complex.

Solution

Use conditional types to define a set of rules for parameter ...

Get TypeScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.