Chapters

  • 0. Introduction

    Free

  • 1. Types & Values

    Free

  • 2. Types are just data

    Free

  • 3. Objects & Records

    Free

  • 4. Arrays & Tuples

    Free

  • 5. Conditional Types
  • 6. Loops with Recursive Types
  • 7. Template Literal Types
  • 8. The Union Type Multiverse
  • 9. Loops with Mapped Types
  • 10. Assignability In Depth

    wip

  • 11. Debugging Types

    wip

Articles

Subscribe

About

Made with ❤️ by @GabrielVergnaud

Code branching with Conditional Types

After learning about the many kinds of types we can play with in the three previous chapters, it's time to implement our first type-level algorithms! We finally get to write some actual code in the language of types. Yay! 🎉🎉🎉

In every programming language, the most basic form of algorithmic logic is code branching. The if and else statements count almost certainly among the first lines of code you have ever written, so I suspect you know how important and widespread they are in programming.

if (trafficLight === "green") go();
else stop();

Being a Turing Complete programming language, the type system of TypeScript of course supports code branching! But what are use cases for executing different code paths in our types, and how would we even do that? Let's find out!

Anatomy of a Conditional Type

In Type-level TypeScript, code branching is known as Conditional Types. The syntax is very similar to the Ternary Operators we use in JavaScript:

Support Type-Level TypeScript!

Become an Early-Bird Member to support the writing of Type-Level TypeScript and get access to all upcoming chapters!

You will find everything you need to become a TypeScript Expert — 11 chapters of in-depth, unique content, and more than 70 fun challenges to practice your new skills.

  • Full access to all 11 chapters

  • 70 type challenges with explanations

  • Lifetime access to all course materials

  • Exclusive discord community

Loading...

⟸ Previous

4. Arrays & Tuples

Next ⟹

6. Loops with Recursive Types