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

Loops with Recursive Types

In our journey to learn the language of types, we've already gone pretty far. In the previous chapter, we started computing types from other types using conditional logic. We used the type system as a programming language for the first time and in this chapter, I want us to explore this idea even further. After code branching, it's time to learn how to write type-level loops!

Loops make programming feel like magic sometimes. It's a wonder that computers can solve such complex problems so quickly given the right algorithm. Computers just excel at repetitive tasks and loops let us tap into their power. There is no reason not to take advantage of this at the type level too!

In this chapter, we will use recursion to loop over tuple types. If you aren't already well-versed in recursive algorithms, the code I'm going to show may look unfamiliar. Bear with me though, and remember that we are not only learning a new programming language but a functional one! It takes time for all of these new concepts to sink in, and being open to some discomfort is the key to making progress.

Let's dive into it!

Two styles of loops

Most programming languages we use today are spiritual children of the C language. They have a similar syntax and are grounded in an imperative programming style. In the imperative style, we tell the computer what to do in a series of instructions that should be executed sequentially, in the right order.

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

5. Code branching with Conditional Types

Next ⟹

7. Template Literal Types