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 — 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...