Chapter 6. Generics and Type-Level Programming
TypeScript’s type system is designed to model the runtime behavior of JavaScript code. Because JavaScript is so dynamic and permissive, this has pushed TypeScript’s type system to develop increasingly powerful capabilities. As Item 15 explained, this includes logic for mapping between types.
When you add generic type aliases to the mix, TypeScript’s type system becomes powerful enough that you can think of it as its own independent programming language. (TypeScript’s type system is Turing Complete, so this is true in a formal sense.) Rather than programming with values, as you do in JavaScript, you’re now programming with types. In other words, type-level programming. This is distinct from metaprogramming (writing programs that operate on programs), though the two terms are sometimes conflated.
Learning new languages is fun, and you can find all sorts of wild applications built using TypeScript’s type system, ranging from games to SQL parsers. This has been driven in part by the Type Challenges project, which includes hundreds of increasingly difficult puzzles to solve in the type system. Solving these as you read this chapter is a great way to cement what you’ve learned.
This chapter also includes a few cautionary notes. Just because TypeScript includes a programming language for types doesn’t mean it’s a particularly intuitive, ergonomic, or pleasant language to work with. Just because you can write logic at the type level doesn’t ...
Get Effective TypeScript, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.