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 Quiz
  • 11. Designing Type-Safe APIs
  • 12. Conclusion

Articles

Subscribe

About

Made with ❤️ by @GabrielVergnaud

|Chapters|Articles

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:

Enroll in Type-Level TypeScript!

Get access to all chapters of the Type-Level TypeScript course and join a community of 1600+ students!

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

  • Full access to all 12 chapters

  • 70 type challenges with explanations

  • Lifetime access to all course materials

  • Exclusive discord community

Loading...

⟸ Previous

4. Arrays & Tuples

Free

Next ⟹

6. Loops with Recursive Types