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: