Stefan Baumgartner TypeScript Cookbook Real World Type-Level Programming
WEB DEVELOPMENT “TypeScript Cookbook shows you how to solve all sorts of problems with advanced types. Even better, it teaches you how to use TypeScript’s features to write new types for yourself.” —Nathan Shively-Sanders Software Engineer on the TypeScript team TypeScript Cookbook Twitter: @oreillymedia linkedin.com/company/oreilly-media youtube.com/oreillymedia TypeScript is one of the most important tools for JavaScript developers. Still, even experienced developers wonder why the TypeScript compiler is throwing squiggly red lines at them. Enter TypeScript Cookbook. With this practical guide, author Stefan Baumgartner provides senior engineers with solutions for everyday TypeScript problems. If you’re conversant with JavaScript and TypeScript basics, this book provides actionable recipes to help you tackle a wide array of issues. From setting up complex project structures to developing advanced helper types, each self-contained recipe guides you through the problem and discusses why and how a solution works. The ideal companion for your ongoing TypeScript journey, this cookbook helps you: • Dive into the inner workings of the TypeScript type system • Integrate TypeScript into a variety of projects • Craft advanced type definitions that allow for flexible scenarios • Create useful helper types that function across projects • Ensure readability along with type safety • Effectively type function signatures that rely on string literals • Work around limitations of the standard library • Integrate TypeScript into advanced React projects • Apply type development strategies, including testing of types • Identify situations where the type system makes exceptions to the rules Stefan Baumgartner is an independent trainer for Rust and TypeScript at oida.dev and a senior product architect at Dynatrace, where he leads the development efforts for TypeScript-based development tools, libraries, and language runtimes. He writes about TypeScript on his popular blog, fettblog.eu, and published his first TypeScript book TypeScript in 50 Lessons with Smashing Magazine in 2020. US $65.99 CAN $82.99 ISBN: 978-1-098-13665-9
Praise for TypeScript Cookbook In TypeScript Cookbook, Stefan Baumgartner deftly covers everything from project setup to advanced typing techniques, providing a wealth of practical examples and valuable insights to make you a TypeScript expert ready for any challenge. —Addy Osmani Head of Chrome Developer Experience, Google Typescript Cookbook is an essential resource for developers who want to learn how to use TypeScript effectively. Stefan packs clear and concise recipes for solving real-world problems into a comprehensive playbook that upskills you from novice to expert. —Simona Cotin Engineering Manager for Angular, Google TypeScript Cookbook shows you how to solve all sorts of problems with advanced types. Even better, it teaches you how to use TypeScript’s features to write new types for yourself. —Nathan Shively-Sanders Software Engineer on the TypeScript team TypeScript Cookbook is an extremely valuable reference for anyone working with TypeScript. It condenses a ton of valuable information into a format you can dip into and out of easily. —Matt Pocock Author of Total TypeScript TypeScript can sometimes slow developers down, but TypeScript Cookbook is the perfect remedy! The comprehensive solutions offered for common TypeScript problems make it an indispensable tool for improving productivity. —Vanessa Böhner Lead Front-End Developer, Zavvy
TypeScript Cookbook is a lovely read and a fount of information. I thoroughly enjoyed the succinct questions and answers followed by well-crafted discussions of the nuances behind them. I learned a ton of neat tricks and snazzy new patterns from each of the chapters. It would behoove any TypeScript developer to learn those nuances, tricks, and patterns—in particular from this book. Would highly recommend! —Josh Goldberg Author of Learning TypeScript I recognized so many issues that I’d come across in my own TypeScript and found Stefan’s advice on them to be clear, precise, and insightful. I feel more confident with TypeScript with this reference by my side. —Phil Nash, Developer Advocate, Sonar
Stefan Baumgartner TypeScript Cookbook Real World Type-Level Programming
978-1-098-13665-9 [LSI] TypeScript Cookbook by Stefan Baumgartner Copyright © 2023 Stefan Baumgartner. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Amanda Quinn Development Editor: Shira Evans Production Editor: Elizabeth Faerm Copyeditor: Piper Editorial Consulting, LLC Proofreader: Shannon Turlington Indexer: WordCo Indexing Services, Inc. Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea August 2023: First Edition Revision History for the First Edition 2023-08-08: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098136659 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. TypeScript Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. Project Setup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Type-Checking JavaScript 2 1.2 Installing TypeScript 6 1.3 Keeping Types on the Side 9 1.4 Migrating a Project to TypeScript 11 1.5 Loading Types from Definitely Typed 13 1.6 Setting Up a Full-Stack Project 16 1.7 Setting Up Tests 21 1.8 Typing ECMAScript Modules from URLs 24 1.9 Loading Different Module Types in Node 27 1.10 Working with Deno and Dependencies 30 1.11 Using Predefined Configurations 33 2. Basic Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.1 Annotating Effectively 35 2.2 Working with any and unknown 39 2.3 Choosing the Right Object Type 42 2.4 Working with Tuple Types 45 2.5 Understanding Interfaces Versus Type Aliases 48 2.6 Defining Function Overloads 50 2.7 Defining this Parameter Types 53 2.8 Working with Symbols 56 2.9 Understanding Value and Type Namespaces 59 v
3. The Type System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 3.1 Modeling Data with Union and Intersection Types 63 3.2 Explicitly Defining Models with Discriminated Union Types 68 3.3 Exhaustiveness Checking with the Assert never Technique 70 3.4 Pinning Types with Const Context 74 3.5 Narrowing Types with Type Predicates 77 3.6 Understanding void 79 3.7 Dealing with Error Types in catch Clauses 82 3.8 Creating Exclusive Or Models with Optional never 85 3.9 Effectively Using Type Assertions 88 3.10 Using Index Signatures 91 3.11 Distinguishing Missing Properties and Undefined Values 95 3.12 Working with Enums 97 3.13 Defining Nominal Types in a Structural Type System 102 3.14 Enabling Loose Autocomplete for String Subsets 106 4. Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 4.1 Generalizing Function Signatures 110 4.2 Creating Related Function Arguments 112 4.3 Getting Rid of any and unknown 116 4.4 Understanding Generic Instantiation 118 4.5 Generating New Object Types 123 4.6 Modifying Objects with Assertion Signatures 127 4.7 Mapping Types with Type Maps 130 4.8 Using ThisType to Define this in Objects 134 4.9 Adding Const Context to Generic Type Parameters 138 5. Conditional Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 5.1 Managing Complex Function Signatures 143 5.2 Filtering with never 147 5.3 Grouping Elements by Kind 151 5.4 Removing Specific Object Properties 157 5.5 Inferring Types in Conditionals 160 6. String Template Literal Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 6.1 Defining a Custom Event System 168 6.2 Creating Event Callbacks with String Manipulation Types and Key Remapping 170 6.3 Writing a Formatter Function 174 6.4 Extracting Format Parameter Types 177 6.5 Dealing with Recursion Limits 180 6.6 Using Template Literals as Discriminants 183 vi | Table of Contents
7. Variadic Tuple Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 7.1 Typing a concat Function 189 7.2 Typing a promisify Function 192 7.3 Typing a curry Function 197 7.4 Typing a Flexible curry Function 200 7.5 Typing the Simplest curry function 203 7.6 Creating an Enum from a Tuple 206 7.7 Splitting All Elements of a Function Signature 210 8. Helper Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 8.1 Setting Specific Properties Optional 213 8.2 Modifying Nested Objects 217 8.3 Remapping Types 220 8.4 Getting All Required Keys 223 8.5 Allowing at Least One Property 226 8.6 Allowing Exactly One and All or None 231 8.7 Converting Union to Intersection Types 235 8.8 Using type-fest 242 9. The Standard Library and External Type Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 9.1 Iterating over Objects with Object.keys 248 9.2 Explicitly Highlighting Unsafe Operations with Type Assertions and unknown 251 9.3 Working with defineProperty 253 9.4 Expanding Types for Array.prototype.includes 259 9.5 Filtering Nullish Values 263 9.6 Extending Modules 264 9.7 Augmenting Globals 267 9.8 Adding Non-JS Modules to the Module Graph 271 10. TypeScript and React. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 10.1 Writing Proxy Components 276 10.2 Writing Controlled Components 279 10.3 Typing Custom Hooks 281 10.4 Typing Generic forwardRef Components 284 10.5 Providing Types for the Context API 288 10.6 Typing Higher-Order Components 293 10.7 Typing Callbacks in React’s Synthetic Event System 296 10.8 Typing Polymorphic Components 299 11. Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 11.1 Choosing the Right Visibility Modifier 304 Table of Contents | vii
11.2 Explicitly Defining Method Overrides 309 11.3 Describing Constructors and Prototypes 313 11.4 Using Generics in Classes 316 11.5 Deciding When to Use Classes or Namespaces 319 11.6 Writing Static Classes 324 11.7 Working with Strict Property Initialization 328 11.8 Working with this Types in Classes 332 11.9 Writing Decorators 336 12. Type Development Strategies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 12.1 Writing Low Maintenance Types 344 12.2 Refining Types Step by Step 346 12.3 Checking Contracts with satisfies 357 12.4 Testing Complex Types 361 12.5 Validating Data Types at Runtime with Zod 363 12.6 Working Around Index Access Restrictions 368 12.7 Deciding Whether to Use Function Overloads or Conditional Types 370 12.8 Naming Generics 377 12.9 Prototyping on the TypeScript Playground 379 12.10 Providing Multiple Library Versions 384 12.11 Knowing When to Stop 387 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 viii | Table of Contents
Foreword I am always excited to witness the evolution of programming languages and the impact they make on software development. TypeScript, a superset of JavaScript, is no exception. In fact, TypeScript has swiftly risen to become one of the most widely used programming languages, carving out a unique space for itself in the world of web development. As this language has garnered significant adoption and praise, it is only fitting that it be given the comprehensive treatment it deserves in TypeScript Cookbook. As an avid TypeScript user, I must say that the precision and robustness it has brought to JavaScript have been both empowering and astonishing. One of the key reasons behind this is its type safety, which has addressed a long-standing criticism of JavaScript. By allowing developers to define strict types for variables, TypeScript has made it easier to catch errors during the compilation process, significantly improving code quality and maintainability. TypeScript Cookbook is a much-needed guide. The preface rightly establishes Type‐ Script’s skyrocketing popularity. However, this rising interest in TypeScript also brings to light the challenges developers face in adopting it. It is here that this book is set to make a difference. Drenched in practicality, this book is meticulously designed to address real-world challenges faced by TypeScript users. It is an amalgamation of more than one hun‐ dred recipes that deal with a gamut of concepts ranging from basic to advanced. As developers, we often find ourselves fighting the type-checker, and that’s where this book will serve as your sword and shield. With in-depth explanations, you will not only learn how to work with TypeScript efficiently but also understand the thought processes behind the concepts. ix
One of the many laudable aspects of TypeScript Cookbook is its approach toward embracing TypeScript’s rapid evolution. With TypeScript getting regular releases per year, staying up to date is a Herculean task. This book does a splendid job focusing on the long-lasting aspects of TypeScript and ensures that your learning remains relevant despite the ever-changing landscape. In addition to a plethora of recipes, the book encourages you to comprehend the intricate connection between JavaScript and TypeScript. Understanding the symbiotic relationship between these two languages is paramount in unlocking TypeScript’s true potential. Whether you are struggling with type assertions, generics, or even integrat‐ ing TypeScript with popular libraries and frameworks such as React, this book covers it all. This book also excels in serving as both a guide and a reference. As a guide, it seam‐ lessly takes you from novice to expert. As a reference, it serves as a reliable compan‐ ion throughout your TypeScript journey. The organization of the book is impeccable, ensuring that each chapter can be consumed in isolation, yet forming a cohesive knowledge base when put together. With TypeScript’s popularity showing no signs of slowing down, TypeScript Cookbook is poised to be an essential resource for every TypeScript enthusiast. From real-world examples to a treasure trove of solutions, this book is the compass you need to navi‐ gate the exciting world of TypeScript. Whether you are getting your feet wet or looking to dive into the depths of Type‐ Script, this book is a beacon of knowledge. I extend my heartfelt congratulations to Stefan Baumgartner for crafting this masterpiece and welcome you all to savor the recipes of success in TypeScript. Let the journey into TypeScript begin. —Addy Osmani Engineering Lead Google Chrome July 2023 x | Foreword
Preface The only way you can read this sentence is by opening this book, either physically or digitally. This tells me you are interested in TypeScript, one of the most popular pro‐ gramming languages in recent years. According to the 2022 State of JavaScript survey, almost 70% of all participants actively use TypeScript. The 2022 StackOverflow sur‐ vey lists TypeScript as one of the top five 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. Without a doubt: TypeScript is a phenomenon! Despite 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 com‐ piler when they know their code has to work. However, 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 than it is designed to deliver? The answer is somewhere in the middle, and this is where TypeScript Cookbook comes in. In this book, you will find more than one hundred 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, as well as the trade- offs and exceptions it has to make to not interfere with its foundation: JavaScript. You also will learn methodologies, design patterns, and development techniques to create better and more robust TypeScript code. In the end, you will understand not only how to do something but also why. 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 the book. With TypeScript’s four releases per year, it’s impossible to list all the most up-to-date features in a single book. This is why we focus on long-lasting aspects of the programming language, to prepare you for all the changes to come. Welcome to the TypeScript cookbook. xi
Who This Book Is For 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 funda‐ mental 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: you need a deeper knowledge of the type system, and you need to actively work with TypeScript not only to ensure a robust and scaleable application but also to guarantee collabora‐ tion between you and your colleagues. You want to learn about how something behaves in TypeScript, as well as understand the reasoning behind its behavior. This is what you get in TypeScript Cookbook. You will learn project setup, quirks, and behavior of the type system; complex types and their use cases; and working with frameworks and applying type development meth‐ odology. 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 fea‐ tures, but also a reference you can rely on throughout your career, this book will do right by you. What’s in This Book? A predominant goal of writing TypeScript Cookbook was to focus on solutions for everyday problems. TypeScript is a remarkable programming language, and the fea‐ tures of the type system are so powerful that we reach a point where people challenge themselves with advanced TypeScript puzzles. While these brain teasers are entertain‐ ing, 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 meth‐ odologies you can use in multiple scenarios, not just in a single recipe. Throughout the book you will find references to earlier recipes, showing you how a specific techi‐ que can be applied in a new context. The examples are either ripped directly from the source code of real projects or strip‐ ped down to essentials to illustrate a concept without requiring too much domain knowledge. While some examples are very specific, you will also see a lot of Person objects that have the name “Stefan” (and you will be able to see me age throughout the book). The book will focus almost exclusively on the features TypeScript adds on top of Java‐ Script; thus, 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 xii | Preface
relationship, some chapters in the book discuss JavaScript features and their behavior, but always through the lens of TypeScript. A cookbook is designed to give you a quick solution to a problem: a recipe. In this book, every recipe ends with a discussion, giving you broader context and meaning for 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. TypeScript Cookbook is unmistakably a discussion book. In my almost 20-year career as a person who writes software, I’ve never encountered situations in which one solution fits all problems. That’s why I want to show you in detail how we came to our conclusions, their mean‐ ing, and the trade-offs. Ultimately, this book should be a guide for discussions like that. Why make an educated guess when you have proper arguments for your decisions? Organization of This Book TypeScript Cookbook 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 explore 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 buildup, each chapter and each recipe can be consumed on its own. Each lesson has been designed to point out the connection to previous (or next!) recipes in the book, but each chapter is ultimately self-contained. Feel free to consume it from start to finish, or use the “choose your own adventure” approach with its many references. Here is a brief overview of the content. TypeScript wants to work with all flavors of JavaScript, and there are a lot of different flavors. In Chapter 1, “Project Setup” 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 differ‐ ence between any and unknown, teaches you which code contributes to which name‐ space, and answers the age-old question of whether to choose a type alias or an inter‐ face 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 under‐ stand why TypeScript has type assertions and no type casts, why enums are generally frowned upon, and how you find the nominal bits in a structural type system. Preface | xiii
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. This chapter marks 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 why the TypeScript type system is also its own metaprogramming language. With the possibility of choosing 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 integrates a string parser 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 describe function parameters and object-like arrays, and it creates flexible helper functions. Even more metaprogramming happens in Chapter 8, “Helper Types”. TypeScript has a few built-in helper types that make it easier for you to derive types from other types. In this chapter, you learn not only how to use them but also how to create your own. This chapter also marks the next breakpoint in TypeScript Cookbook because at this point you have learned all the basic ingredients of the language and type system, which you then can apply in the next part. After spending eight chapters understanding all the nitty-gritty of the type system, it’s time to integrate your knowledge with type definitions done by others in Chapter 9, “The Standard Library and External Type Definitions”. In this chapter you will see situations that work differently than expected, and see how you can bend the built-in type definitions to your will. In Chapter 10, “TypeScript and React” you will learn how one of the most popular JavaScript frameworks is integrated in TypeScript, features that make the syntax extension JSX possible, and how this fits into the overall concept of TypeScript. You will also learn how to write 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 about classes, a staple of object-oriented programming that was available in TypeScript long before their counterpart existed in JavaScript. This leads to an interesting duality of features discussed in detail in Chapter 11, “Classes”. The book ends with Chapter 12, “Type Development Strategies”. Here I focus on giv‐ ing you the skills to create advanced types on your own, to make the right decisions xiv | Preface
on how to move your project along, and to deal with libraries that validate types for you. You also will learn about special workarounds and hidden features, and discuss how to name generics or if advanced types are a bit too much. This chapter is particu‐ larly fun because after a long journey from novice to apprentice, you will reach expert status. All examples are available as a TypeScript playground or CodeSandbox project at the book’s website. The playgrounds in particular offer an intermediate state, so you can fiddle around on your own and play with the behaviors. I always say that you can’t learn a programming language just by reading about it; you need to actively code and get your hands dirty to understand how everything plays together. See this as an invi‐ tation to have fun with programming types. Conventions Used in This Book Programming Conventions 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 semicolons after each property declaration of your types—you are more than welcome to continue with your preference. TypeScript Cookbook has a lot of examples and 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 for technical reasons. All examples have been checked against TypeScript 5.0, the most recent release at the time of this book’s writing. TypeScript changes constantly and so do the rules. This book ensures that we mostly focus on things that are long-lasting and can be trusted across versions. Where I expect further development or fundamental change, I pro‐ vide respective warnings and notes. Preface | xv
Typesetting Conventions The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://typescript-cookbook.com. If you have a technical question or a problem using the code examples, please send email to support@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 xvi | Preface
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 do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “TypeScript Cookbook by Stefan Baumgartner (O’Reilly). Copyright 2023 Stefan Baumgartner, 978-1-098-13665-9.” 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. O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy 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. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) support@oreilly.com https://www.oreilly.com/about/contact.html 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. Preface | xvii
Follow us on Twitter: https://twitter.com/oreillymedia. Watch us on YouTube: https://youtube.com/oreillymedia. Acknowledgments 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 not only are entertaining but also provide me with the necessary feed‐ back to evaluate all my choices. They are the first people that heard about 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. Phil Nash, Simona Cotin, and Vanessa Böhner have not only been early reviewers of the final manuscript but also long-time companions and friends who are always here to sanity-check my ideas. Addy Osmani has been an inspiration throughout my entire career, and I’m very proud that he agreed to open my new book. 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 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 reasoning made sense and that I didn’t skip a beat. Their love of detail and their ability to discuss on such a high level ensured 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 not for Amanda Quinn. After writing TypeScript in 50 Lessons in 2020, I thought I’d said everything I needed to say about TypeScript. It was Amanda who pursued me to give the idea of a cookbook a go, to see which ideas 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 one hundred entries. Amanda was right: I had so much more to say, and I’m eternally grateful for her support and her guidance. xviii | Preface
Comments 0
Loading comments...
Reply to Comment
Edit Comment