Preface

In the spring of 2016, I visited my old coworker Evan Martin at Google’s San Francisco office and asked him what he was excited about. I’d asked him this same question many times over the years because the answers were wide-ranging and unpredictable but always interesting: C++ build tools, Linux audio drivers, online crosswords, emacs plugins. This time, Evan was excited about TypeScript and Visual Studio Code.

I was surprised! I’d heard of TypeScript before, but I knew only that it was created by Microsoft and that I mistakenly believed it had something to do with .NET. As a lifelong Linux user, I couldn’t believe that Evan had hopped on team Microsoft.

Then Evan showed me vscode and the TypeScript playground and I was instantly converted. Everything was so fast, and the code intelligence made it easy to build a mental model of the type system. After years of writing type annotations in JSDoc comments for the Closure Compiler, this felt like typed JavaScript that really worked. And Microsoft had built a cross-platform text editor on top of Chromium? Perhaps this was a language and toolchain worth learning.

I’d recently joined Sidewalk Labs and was writing our first JavaScript. The codebase was still small enough that Evan and I were able to convert it all to TypeScript over the next few days.

I’ve been hooked ever since. TypeScript is more than just a type system. It also brings a whole suite of language services which are fast and easy to use. The cumulative effect is that TypeScript doesn’t just make JavaScript development safer: it also makes it more fun!

Who This Book Is For

The Effective books are intended to be the “standard second book” on their topic. You’ll get the most out of Effective TypeScript if you have some previous practical experience working with JavaScript and TypeScript. My goal with this book is not to teach you TypeScript or JavaScript but to help you advance from a beginning or intermediate user to an expert. The items in this book do this by helping you build mental models of how TypeScript and its ecosystem work, making you aware of pitfalls and traps to avoid, and by guiding you toward using TypeScript’s many capabilities in the most effective ways possible. Whereas a reference book will explain the five ways that a language lets you do X, an Effective book will tell you which of those five to use and why.

TypeScript has evolved rapidly over the past few years, but my hope is that it has stabilized enough that the content in this book will remain valid for years to come. This book focuses primarily on the language itself, rather than any frameworks or build tools. You won’t find any examples of how to use React or Angular with TypeScript, or how to configure TypeScript to work with webpack, Babel, or Rollup. The advice in this book should be relevant to all TypeScript users.

Why I Wrote This Book

When I first started working at Google, I was given a copy of the third edition of Effective C++. It was unlike any other programming book I’d read. It made no attempt to be accessible to beginners or to be a complete guide to the language. Rather than telling you what the different features of C++ did, it told you how you should and should not use them. It did so through dozens of short, specific items motivated by concrete examples.

The effect of reading all these examples while using the language daily was unmistakable. I’d used C++ before, but for the first time I felt comfortable with it and knew how to think about the choices it presented me. In later years I would have similar experiences reading Effective Java and Effective JavaScript.

If you’re already comfortable working in a few different programming languages, then diving straight into the odd corners of a new one can be an effective way to challenge your mental models and learn what makes it different. I’ve learned an enormous amount about TypeScript from writing this book. I hope you’ll have the same experience reading it!

How This Book Is Organized

This book is a collection of “items,” each of which is a short technical essay that gives you specific advice about some aspect of TypeScript. The items are grouped thematically into chapters, but feel free to jump around and read whichever ones look most interesting to you.

Each item’s title conveys the key takeaway. These are the things you should remember as you’re using TypeScript, so it’s worth skimming the table of contents to get them in your head. If you’re writing documentation, for example, and have a nagging sense that you shouldn’t be writing type information, then you’ll know to go read Item 30: Don’t repeat type information in documentation.

The text of the item motivates the advice in the title and backs it up with concrete examples and technical arguments. Almost every point made in this book is demonstrated through example code. I tend to read technical books by looking at the examples and skimming the prose, and I assume you do something similar. I hope you’ll read the prose and explanations! But the main points should still come across if you skim the examples.

After reading the item, you should understand why it will help you use TypeScript more effectively. You’ll also know enough to understand if it doesn’t apply to your situation. Scott Meyers, the author of Effective C++, gives a memorable example of this. He met a team of engineers who wrote software that ran on missiles. They knew they could ignore his advice about preventing resource leaks, because their programs would always terminate when the missile hit the target and their hardware blew up. I’m not aware of any missiles with JavaScript runtimes, but the James Webb Space Telescope has one, so you never know!

Finally, each item ends with “Things to Remember.” These are a few bullet points that summarize the item. If you’re skimming through, you can read these to get a sense for what the item is saying and whether you’d like to read more. You should still read the item! But the summary will do in a pinch.

Conventions in TypeScript Code Samples

All code samples are TypeScript except where it’s clear from context that they are JSON, GraphQL, or some other language. Much of the experience of using TypeScript involves interacting with your editor, which presents some challenges in print. I’ve adopted a few conventions to make this work.

Most editors surface errors using squiggly underlines. To see the full error message, you hover over the underlined text. To indicate an error in a code sample, I put squiggles in a comment line under the place where the error occurs:

let str = 'not a number';
let num: number = str;
 // ~~~ Type 'string' is not assignable to type 'number'

I occasionally edit the error messages for clarity and brevity, but I never remove an error. If you copy/paste a code sample into your editor, you should get exactly the errors indicated, no more no less.

To draw attention to the lack of an error, I use // OK:

let str = 'not a number';
let num: number = str as any;  // OK

You should be able to hover over a symbol in your editor to see what TypeScript considers its type. To indicate this in text, I use a comment starting with “type is”:

let v = {str: 'hello', num: 42};  // Type is { str: string; num: number; }

The type is for the first symbol on the line (v in this case) or for the result of a function call:

'four score'.split(' ');  // Type is string[]

This matches the type you’d see in your editor character for character. In the case of function calls you may need to assign to a temporary variable to see the type.

I will occasionally introduce no-op statements to indicate the type of a variable on a specific line of code:

function foo(x: string|string[]) {
  if (Array.isArray(x)) {
    x;  // Type is string[]
  } else {
    x;  // Type is string
  }
}

The x; lines are only there to demonstrate the type in each branch of the conditional. You don’t need to (and shouldn’t) include statements like this in your own code.

Unless it’s otherwise noted or clear from context, code samples are intended to be checked with the --strict flag. All samples were verified using TypeScript 3.7.0-beta.

Typographical Conventions Used in This Book

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 elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This element signifies a tip or suggestion.

Note

This element signifies a general note.

Warning

This element indicates a warning or caution.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/danvk/effective-typescript.

If you have a technical question or a problem using the code examples, please send email to .

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: “Effective TypeScript by Dan Vanderkam (O’Reilly). Copyright 2020 Dan Vanderkam, 978-1-492-05374-3.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

O’Reilly Online Learning

Note

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, conferences, 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, please visit http://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)

You can access the web page for this book, where we list errata, examples, and any additional information, at https://oreil.ly/Effective_TypeScript.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

There are many people who helped make this book possible. Thanks to Evan Martin for introducing me to TypeScript and showing me how to think about it. To Douwe Osinga for connecting me with O’Reilly and being supportive of the project. To Brett Slatkin for advice on structure and for showing me that someone I knew could write an Effective book. To Scott Meyers for coming up with this format and for his “Effective Effective Books” blog post, which provided essential guidance.

To my reviewers, Rick Battagline, Ryan Cavanaugh, Boris Cherny, Yakov Fain, Jesse Hallett, and Jason Killian. To all my coworkers at Sidewalk who learned TypeScript with me over the years. To everyone at O’Reilly who helped make this book happen: Angela Rufino, Jennifer Pollock, Deborah Baker, Nick Adams, and Jasmine Kwityn. To the TypeScript NYC crew, Jason, Orta, and Kirill, and to all the speakers. Many items were inspired by talks at the Meetup, as described in the following list:

  • Item 3 was inspired by a blog post of Evan Martin’s that I found particularly enlightening as I was first learning TypeScript.

  • Item 7 was inspired by Anders’s talk about structural typing and keyof relationships at TSConf 2018, and by a talk of Jesse Hallett’s at the April 2019 TypeScript NYC Meetup.

  • Both Basarat’s guide and helpful answers by DeeV and GPicazo on Stack Overflow were essential in writing Item 9.

  • Item 10 builds on similar advice in Item 4 of Effective JavaScript (Addison-Wesley).

  • I was inspired to write Item 11 by mass confusion around this topic at the August 2019 TypeScript NYC Meetup.

  • Item 13 was greatly aided by several questions about type vs. interface on Stack Overflow. Jesse Hallett suggested the formulation around extensibility.

  • Jacob Baskin provided encouragement and early feedback on Item 14.

  • Item 19 was inspired by several code samples submitted to the r/typescript subreddit.

  • Item 26 is based on my own writing on Medium and a talk I gave at the October 2018 TypeScript NYC Meetup.

  • Item 28 is based on common advice in Haskell (“make illegal states unrepresentable”). The Air France 447 story is inspired by Jeff Wise’s incredible 2011 article in Popular Mechanics.

  • Item 29 is based on an issue I ran into with the Mapbox type declarations. Jason Killian suggested the phrasing in the title.

  • The advice about naming in Item 36 is common but this particular formulation was inspired by Dan North’s short article in 97 Things Every Programmer Should Know (O’Reilly).

  • Item 37 was inspired by Jason Killian’s talk at the very first TypeScript NYC Meetup in September 2017.

  • Item 41 is based on the TypeScript 2.1 release notes. The term “evolving any” is not widely used outside the TypeScript compiler itself, but I find it useful to have a name for this unusual pattern.

  • Item 42 was inspired by a blog post of Jesse Hallett’s. Item 43 was greatly aided by feedback from Titian Cernicova Dragomir in TypeScript issue #33128.

  • Item 44 is based on York Yao’s work on the type-coverage tool. I wanted something like this and it existed!

  • Item 46 is based on a talk I gave at the December 2017 TypeScript NYC Meetup.

  • Item 50 owes a debt of gratitude to David Sheldrick’s post on the Artsy blog on conditional types, which greatly demystified the topic for me.

  • Item 51 was inspired by a talk Steve Faulkner aka southpolesteve gave at the February 2019 Meetup.

  • Item 52 is based on my own writing on Medium and work on the typings-checker tool, which eventually got folded into dtslint.

  • Item 53 was inspired/reinforced by Kat Busch’s Medium post on the various types of enums in TypeScript, as well as Boris Cherny’s writings on this topic in Programming TypeScript (O’Reilly).

  • Item 54 was inspired by my own confusion and that of my coworkers on this topic. The definitive explanation is given by Anders on TypeScript PR #12253.

  • The MDN documentation was essential for writing Item 55.

  • Item 56 is loosely based on Item 35 of Effective JavaScript (Addison-Wesley).

  • Chapter 8 is based on my own experience migrating the aging dygraphs library.

I found many of the blog posts and talks that led to this book through the excellent r/typescript subreddit. I’m particularly grateful to developers who provided code samples there which were essential for understanding common issues in beginner TypeScript. Thanks to Marius Schulz for the TypeScript Weekly newsletter. While it’s only occasionally weekly, it’s always an excellent source of material and a great way to keep up with TypeScript. To Anders, Daniel, Ryan, and the whole TypeScript team at Microsoft for the talks and all the feedback on issues. Most of my issues were misunderstandings, but there is nothing quite so satisfying as filing a bug and immediately seeing Anders Hejlsberg himself fix it! Finally, thanks to Alex for being so supportive during this project and so understanding of all the working vacations, mornings, evenings, and weekends I needed to complete it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.171.235