The only way you are able to read this sentence is by opening this specific book, either physically or digitally. This tells me that you are undoubtedly interested in TypeScript, one of the most popular programming languages in recent years.
According to the 2022 State of JavaScript survey, almost 70% of all participants actively use TypeScript. The 2022 StackOverflow survey lists TypeScript as one of the top 5 most popular languages and the fourth highest in user satisfaction. At the beginning of 2023, TypeScript counts more than 40 million weekly downloads on NPM.
There is no doubt: TypeScript is a phenomenon!
Despite all its popularity, TypeScript still gives a lot of developers a hard time. Fighting the type checker is one phrase you hear often, another one is throwing a couple of any’s in there so it shuts up. Some people feel slowed down, writing just to please the compiler when they know that their code has to work. This is an odd situation. TypeScript’s sole purpose is to make JavaScript developers more productive and efficient. Does the tool ultimately fail to meet its goals, or do we as developers expect something different from the tool?
The answer is somewhere in the middle, and this is where the TypeScript cookbook comes in. In this book, you will find more than 100 recipes that deal with everything from complex project setups to advanced typing techniques. You will learn about the intricacies and inner workings of the type system, and the trade-offs and exceptions it has to make to not interfere with its foundation: JavaScript. You will also learn methodologies, design patterns, and development techniques to create better, and more robust TypeScript code. In the end, you will not only understand how something is done but also the reasoning behind it.
My goal is to give you a guide that takes you from novice to expert, as well as a quick reference you can use well after you’ve read through the book. With TypeScript getting four releases per year, it’s impossible to get all the most up-to-date features listed in a single book. This is why we focus on long-lasting aspects of the programming language, to make you prepared for all the changes that are to come.
Welcome to the TypeScript cookbook.
This book is for developers, engineers, and architects who know enough JavaScript to be dangerous and have gotten their feet wet in TypeScript. You understand the fundamental concepts of types and how to apply them, and you understand the immediate benefits of static types. You are at a point where things get interesting, where you need a deeper knowledge of the type system, and where you need to actively work with TypeScript to not only ensure a robust and scaleable application but also guarantee collaboration between you and your colleagues.
You not only want to learn about how something behaves in TypeScript, but also understand the reasoning behind its behavior. This is what you get in the TypeScript cookbook. You will learn everything from project setup, quirks, and behavior of the type system, complex types and their use-cases, up to working with frameworks and applying type development methodology. This book is designed to take you from novice to apprentice, and eventually to expert. If you need a guide to actively learn more of TypeScript’s sophisticated features, but also a reference you can rely on throughout your career, this book will do right by you.
A predominant goal of writing the TypeScript cookbook was to focus on solutions for everyday problems. TypeScript is a remarkable programming language, and the features of the type system are so powerful that we reach a point where people challenge themselves with advanced TypeScript puzzles. While those brain teasers are entertaining, they often lack real-world context and thus are not part of this book.
I want to make sure that the content presented is something you will encounter in your day-to-day life as a TypeScript developer, with problems that stem from real-world situations, and solutions that are holistic. I will teach you techniques and methodologies which can be used in multiple scenarios, not just in a single recipe. Throughout the book you will find references to earlier recipes, showing you how a specific techique can be applied in a new context.
The examples are either ripped out directly from the source code of real projects, or stripped down to essentials to illustrate a concept without too much domain knowledge. While some examples are very specific, you will also see a lot of Person objects that have a name of “Stefan” (and you will be able to see me age throughout the book).
The cookbook will focus almost exclusively on the features TypeScript adds on top of JavaScript, which means to understand the example fully, you need to understand a reasonable amount of JavaScript. I don’t expect you to be a JavaScript guru, but being able to read basic JavaScript code is a must. Since JavaScript and TypeScript have this strong relationship, there are also chapters in the book where we discuss JavaScript features and their behavior, but always through the lens of TypeScript.
A cookbook’s idea is to give you a quick solution to a problem, forming a recipe. Every recipe ends with a discussion, giving you broader context and meaning to the solution. Depending on the style of the author, the focus of O’Reilly’s cookbooks lies either on the solution or on the discussion. The TypeScript cookbook is unmistakenly a discussion book. In my almost 20-year-long career as a person who writes software, I’ve never encountered situations where one solution fits all problems, that’s why I want to show you in detail how we came to our conclusions, what they mean, and what the trade-offs are. Ultimately, this book should be a guide for you for discussions like that. Why make an educated guess if you have proper arguments for your decisions?
The TypeScript cookbook serves as a guide that takes you through the language from start to finish. We start with project setup, talk about basic types and the inner workings of the type system, and ultimately go into advanced territory like conditional types and helper types. We continue with chapters that talk about very specific features like the duality of classes and support for React and end with learnings on how to best approach type development.
While there is a thread and build-up, each chapter and each recipe can be consumed on its own. Each lesson has been designed so it points out the connection to previous (or next!) recipes in the book but is ultimately self-contained. Feel free to consume it from start to finish, or go “choose your own adventure” style with all its many references.
I start with Chapter 1: Project Setup. TypeScript wants to work with all flavors of JavaScript, and there are a lot of different flavors. You will learn about configuration possibilities for different language runtimes, module systems, and target platforms.
Chapter 2: Basic Types guides you through the type hierarchy, tells you the difference between any and unknown, teaches you which code contributes to which namespace, and answers the age-old question of whether to choose a type alias or an interface to describe your object types.
One of the longer chapters in the book is Chapter 3: The Type System. Here you will learn everything about union and intersection types, how to define discriminated union types, how to use the assert never and optional never techniques, and how to narrow and widen types based on your use case. After this chapter, you will understand why TypeScript has type assertions and no type casts, why enums are generally been frowned upon, and how you find the nominal bits in a structural type system.
TypeScript has a generic type system, which we will see in detail in Chapter 4: Generics. Generics not only make your code more reusable but are also the entrance to the more advanced features of TypeScript. You can see this chapter as the point where you ascend from TypeScript basics to the more sophisticated areas of the type system. A fitting end to the first part.
Chapter 5: Conditional Types explains to you why the TypeScript type system is also its own meta-programming language. With the possibility to choose types based on certain conditions, people invented the most outstanding things, like a full-fledged SQL parser or a dictionary in the type system. We use conditional types as a tool to make a static type system more flexible for dynamic situations.
In Chapter 6: String Template Literal Types you see how TypeScript has a string parser integrated in the type system. Extracting names from format strings, defining a dynamic event system based on string input, and creating identifiers dynamically, nothing seems impossible!
You get a little taste of functional programming in Chapter 7: Variadic Tuple Types. The tuple has a special meaning in TypeScript and helps us describe function parameters, and object-like arrays, and create flexible helper functions.
Even more meta-programming happens in Chapter 8: Helper Types. TypeScript has a few helper types built-in that make it easier for you to derive types from other types. In this chapter, we not only learn how to use them but also how to create our own. This chapter describes the next breakpoint in the TypeScript cookbook because after it you learned all the basic ingredients of the language and type system, which you then can apply in the next part.
After we spent eight chapters understanding all the nitty-gritty of the type system, it’s time to integrate our knowledge with type definitions done by others in Chapter 9: The Standard Library and External Type Definitions. We see situations that work differently than we thought they would, and we see how we can bend the built-in type definitions to our will.
In Chapter 10: TypeScript and React you will learn about how one of the most popular JavaScript frameworks is integrated in TypeScript, which features make the syntax extension JSX possible, and how this fits into the overall concept of TypeScript. You will also learn how to write good and robust types for components and hooks, and how to deal with a type definition file that has been attached to the actual library after the fact.
The next chapter is a special one. Classes are a staple of object-oriented programming that has been available in TypeScript long before their counterpart in JavaScript started to exist. This leads to an interesting duality of features which we are going to discuss in detail in Chapter 11: Classes.
The book ends with Chapter 12: Type Development Strategies. Here I focus on giving you the skills to create advanced types on your own, to make the right decisions on how to move your project along, and to deal with libraries that validate types for you. You also learn about special workarounds, and hidden features, and discuss with me how to name generics or if advanced types can be a bit too much. This chapter is particularly fun because after a long journey from novice to apprentice, you will be able to reach expert status.
All examples are available as TypeScript playground or Codesandbox project at the book’s website. The playgrounds in particular offer an intermediate state, so you can take it on your own to fiddle around and play with the behavior. I always say that you can’t learn a programming language by only reading about it, you need to actively code and get your hands dirty to understand how everything plays together. See this as an invitation to have fun with programming types.
TypeScript allows for many programming styles and formatting options. To avoid bike-shedding, I chose to autoformat all examples using Prettier. If you are used to a different formatting style — maybe you prefer commas instead of semi-colons after each property declaration of your types — you are more than welcome to continue with your preference.
The TypeScript cookbook has a lot of examples, and also deals with a lot of functions. There are many ways to write functions, and I’ve chosen to write mostly function declarations instead of function expressions, except where it was crucial to explain the differences between both notations. On all other occasions, it’s mostly a matter of taste rather than technical reasons.
All examples have been checked against TypeScript 5.0, the most recent release at the time of its writing. TypeScript changes constantly and so are the rules. This book ensures that we mostly focus on things that are long-lasting and can be trusted across versions. Where things are supposed to develop further or change fundamentally, I made respective warnings and notes.
The following typographical conventions are used in this book:
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant widthUsed for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.
Constant width boldShows commands or other text that should be typed literally by the user.
Constant width italicShows text that should be replaced with user-supplied values or by values determined by context.
This element signifies a tip or suggestion.
This element signifies a general note.
This element indicates a warning or caution.
Supplemental material (code examples, exercises, etc.) is available at https://typescript-cookbook.com.
If you have a technical question or a problem using the code examples, please send email to bookquestions@oreilly.com.
This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.
We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Book Title by Some Author (O’Reilly). Copyright 2012 Some Copyright Holder, 978-0-596-xxxx-x.”
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com.
For more than 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed.
Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com.
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/typescript-cookbook.
For news and information about our books and courses, visit https://oreilly.com.
Find us on LinkedIn: https://linkedin.com/company/oreilly-media.
Follow us on Twitter: https://twitter.com/oreillymedia.
Watch us on YouTube: https://youtube.com/oreillymedia.
Alexander Rosemann, Sebastian Gierlinger, Dominik Angerer, and Georg Kothmeier are the first people I go to if I have something new cooking. Our regular meetings and interactions are not only entertaining but provide me with the necessary feedback to evaluate all my choices. They are the first people that heard from the book, and also the first ones that gave feedback.
Interacting with Matt Pocock, Joe Previte, Dan Vanderkam, Nathan Shively-Sanders, and Josh Goldberg on social media brought plenty of new ideas to the table. Their approach to TypeScript might differ from mine, but they ultimately broadened my horizon and made sure that I didn’t end up too opinionated.
Lena Matscheko, Alexandra Rapeanu, and Mike Kuss did not hesitate to bombard me with technical challenges and questions based on their real-world experiences. Where I lacked a good example, they flooded me with the excellent source material to distill.
I would lose track of all of TypeScript’s developments if it wasn’t for Peter Kröner, who constantly knocks on my door when there’s a new TypeScript version coming out. Our podcast episodes together on TypeScript releases are legendary, and also increasingly not about TypeScript.
My tech editors Mark Halpin, Fabian Friedl and Bernhard Mayr provided the best technical feedback I could wish for. They challenged every assumption, checked on every code sample, and made sure all my reasonings made sense and that I didn’t skip a beat. Their love to detail and their ability to discuss on such a high level made sure that this book is not just another collection of hot takes, but a guide and reference that stands on a solid foundation.
This book would not exist if it wasn’t for Amanda Quinn. After writing TypeScript in 50 Lessons in 2020, I thought everything I had to say about TypeScript was in this particular book. It was Amanda who pursued me to give the idea of a cookbook a go, to see which things I would find that wouldn’t make the cut for my first book. After three hours I had a complete proposal and table of contents with more than 100 entries. Amanda was right, I had so much more to say, and I’m eternally grateful for her support and her guidance.
Where Amanda helped in the early phases, it was Shira Evans who made sure that the project made good progress and didn’t derail at one point or the other. Her feedback was invaluable, and her pragmatic and hands-down approach made it a joy to work together.
During writing phases I had great assistance by the likes of Porcupine Tree, Beck, Nobuo Uematsu, Camel, The Beta Band, and many, many others.
The biggest contribution to this book comes from my family. Doris, Clemens, and Aaron are everything I’ve ever wished for, and without their endless love and support, I wouldn’t be able to pursue my ambitions. Thank you for everything.