Statistics
62
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-11-30
Support
Share

AuthorDan Vanderkam

TypeScript is a typed superset of JavaScript with the potential to solve many of the headaches for which JavaScript is famous. But TypeScript has a learning curve of its own, and understanding how to use it effectively can take time. This book guides you through 62 specific ways to improve your use of TypeScript. Author Dan Vanderkam, a principal software engineer at Sidewalk Labs, shows you how to apply these ideas, following the format popularized by Effective C++ and Effective Java (both from Addison-Wesley). You’ll advance from a beginning or intermediate user familiar with the basics to an advanced user who knows how to use the language well. Effective TypeScript is divided into eight chapters: Getting to Know TypeScript TypeScript’s Type System Type Inference Type Design Working with any Types Declarations and @types Writing and Running Your Code Migrating to TypeScript

Tags
No tags
ISBN: 1492053716
Publisher: O'Reilly Media
Publish Year: 2019
Language: 英文
Pages: 266
File Format: PDF
File Size: 6.9 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Dan Vanderkam Effective TypeScript 62 Specific Ways to Improve Your TypeScript
Praise for Effective TypeScript “Effective TypeScript explores the most common questions we see when working with TypeScript and provides practical, results-oriented advice. Regardless of your level of TypeScript experience, you can learn something from this book.” —Ryan Cavanaugh, Engineering Lead for TypeScript at Microsoft “This book is packed with practical recipes and must be kept on the desk of every professional TypeScript developer. Even if you think you know TypeScript already, get this book and you won’t regret it.” —Yakov Fain, Java Champion “TypeScript is taking over the development world...The deeper understanding of TypeScript this book provides will help many developers shine as they take advantage of TypeScript’s powerful features.” —Jason Killian, Cofounder of TypeScript NYC and former TSLint maintainer “This book is not just about what TypeScript can do—it teaches why each language feature is useful, and where to apply patterns to get the greatest effect. The book focuses on practical advice that will be useful in day-to-day work, with just enough theory to give the reader a deep understanding of how everything works. I consider myself to be an advanced TypeScript user, and I learned a number of new things from this book.” —Jesse Hallett, Senior Software Engineer, Originate, Inc.
Dan Vanderkam Effective TypeScript 62 Specific Ways to Improve Your TypeScript Boston Farnham Sebastopol TokyoBeijing
978-1-492-05374-3 [LSI] Effective TypeScript by Dan Vanderkam Copyright © 2020 Dan Vanderkam. 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: Jennifer Pollock Development Editor: Angela Rufino Production Editor: Deborah Baker Copyeditor: Jasmine Kwityn Proofreader: Kim Wimpsett Indexer: Judith McConville Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest November 2019: First Edition Revision History for the First Edition 2019-10-16: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492053743 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Effective TypeScript, 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.
For Alex. You’re just my type.
(This page has no text content)
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. Getting to Know TypeScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Item 1: Understand the Relationship Between TypeScript and JavaScript 1 Item 2: Know Which TypeScript Options You’re Using 7 Item 3: Understand That Code Generation Is Independent of Types 10 Item 4: Get Comfortable with Structural Typing 16 Item 5: Limit Use of the any Type 20 2. TypeScript’s Type System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Item 6: Use Your Editor to Interrogate and Explore the Type System 25 Item 7: Think of Types as Sets of Values 29 Item 8: Know How to Tell Whether a Symbol Is in the Type Space or Value Space 35 Item 9: Prefer Type Declarations to Type Assertions 40 Item 10: Avoid Object Wrapper Types (String, Number, Boolean, Symbol, BigInt) 43 Item 11: Recognize the Limits of Excess Property Checking 46 Item 12: Apply Types to Entire Function Expressions When Possible 49 Item 13: Know the Differences Between type and interface 52 Item 14: Use Type Operations and Generics to Avoid Repeating Yourself 56 Item 15: Use Index Signatures for Dynamic Data 64 Item 16: Prefer Arrays, Tuples, and ArrayLike to number Index Signatures 67 Item 17: Use readonly to Avoid Errors Associated with Mutation 71 Item 18: Use Mapped Types to Keep Values in Sync 77 3. Type Inference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Item 19: Avoid Cluttering Your Code with Inferable Types 81 vii
Item 20: Use Different Variables for Different Types 87 Item 21: Understand Type Widening 90 Item 22: Understand Type Narrowing 93 Item 23: Create Objects All at Once 96 Item 24: Be Consistent in Your Use of Aliases 99 Item 25: Use async Functions Instead of Callbacks for Asynchronous Code 102 Item 26: Understand How Context Is Used in Type Inference 107 Item 27: Use Functional Constructs and Libraries to Help Types Flow 111 4. Type Design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Item 28: Prefer Types That Always Represent Valid States 117 Item 29: Be Liberal in What You Accept and Strict in What You Produce 122 Item 30: Don’t Repeat Type Information in Documentation 125 Item 31: Push Null Values to the Perimeter of Your Types 127 Item 32: Prefer Unions of Interfaces to Interfaces of Unions 131 Item 33: Prefer More Precise Alternatives to String Types 134 Item 34: Prefer Incomplete Types to Inaccurate Types 138 Item 35: Generate Types from APIs and Specs, Not Data 142 Item 36: Name Types Using the Language of Your Problem Domain 147 Item 37: Consider “Brands” for Nominal Typing 149 5. Working with any. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 Item 38: Use the Narrowest Possible Scope for any Types 153 Item 39: Prefer More Precise Variants of any to Plain any 155 Item 40: Hide Unsafe Type Assertions in Well-Typed Functions 157 Item 41: Understand Evolving any 159 Item 42: Use unknown Instead of any for Values with an Unknown Type 162 Item 43: Prefer Type-Safe Approaches to Monkey Patching 166 Item 44: Track Your Type Coverage to Prevent Regressions in Type Safety 168 6. Types Declarations and @types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Item 45: Put TypeScript and @types in devDependencies 171 Item 46: Understand the Three Versions Involved in Type Declarations 173 Item 47: Export All Types That Appear in Public APIs 177 Item 48: Use TSDoc for API Comments 178 Item 49: Provide a Type for this in Callbacks 181 Item 50: Prefer Conditional Types to Overloaded Declarations 185 Item 51: Mirror Types to Sever Dependencies 187 Item 52: Be Aware of the Pitfalls of Testing Types 189 7. Writing and Running Your Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 Item 53: Prefer ECMAScript Features to TypeScript Features 195 viii | Table of Contents
Item 54: Know How to Iterate Over Objects 200 Item 55: Understand the DOM hierarchy 202 Item 56: Don’t Rely on Private to Hide Information 207 Item 57: Use Source Maps to Debug TypeScript 210 8. Migrating to TypeScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 Item 58: Write Modern JavaScript 216 Item 59: Use @ts-check and JSDoc to Experiment with TypeScript 223 Item 60: Use allowJs to Mix TypeScript and JavaScript 228 Item 61: Convert Module by Module Up Your Dependency Graph 229 Item 62: Don’t Consider Migration Complete Until You Enable noImplicitAny 234 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Table of Contents | ix
(This page has no text content)
Preface In the spring of 2016, I visited my old coworker Evan Martin at Google’s San Fran‐ cisco office and asked him what he was excited about. I’d asked him this same ques‐ tion 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 life‐ long 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 xi
teach you TypeScript or JavaScript but to help you advance from a beginning or inter‐ mediate 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 sta‐ bilized 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 unmistak‐ able. 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 chal‐ lenge your mental models and learn what makes it different. I’ve learned an enor‐ mous 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 themati‐ cally 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 xii | Preface
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 demon‐ strated through example code. I tend to read technical books by looking at the exam‐ ples 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 sit‐ uation. 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 Type‐ Script 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 squig‐ gles 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. Preface | xiii
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 con‐ siders 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 func‐ tion 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 ele‐ ments 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. xiv | Preface
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://github.com/danvk/effective-typescript. 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 per‐ mission. 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 permissions@oreilly.com. Preface | xv
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, 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 bookques‐ tions@oreilly.com. For more information about our books, courses, conferences, and news, see our web‐ site 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 xvi | Preface
an Effective book. To Scott Meyers for coming up with this format and for his “Effec‐ tive 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 relation‐ ships 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 Over‐ flow 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 sub‐ reddit. • 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 unrepresenta‐ ble”). 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. Preface | xvii
• 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 some‐ thing 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 Feb‐ ruary 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 Pro‐ gramming 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 sam‐ ples there which were essential for understanding common issues in beginner Type‐ Script. 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 misun‐ derstandings, 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, eve‐ nings, and weekends I needed to complete it. xviii | Preface
CHAPTER 1 Getting to Know TypeScript Before we dive into the details, this chapter helps you understand the big picture of TypeScript. What is it and how should you think about it? How does it relate to Java‐ Script? Are its types nullable or are they not? What’s this about any? And ducks? TypeScript is a bit unusual as a language in that it neither runs in an interpreter (as Python and Ruby do) nor compiles down to a lower-level language (as Java and C do). Instead, it compiles to another high-level language, JavaScript. It is this Java‐ Script that runs, not your TypeScript. So TypeScript’s relationship with JavaScript is essential, but it can also be a source of confusion. Understanding this relationship will help you be a more effective TypeScript developer. TypeScript’s type system also has some unusual aspects that you should be aware of. Later chapters cover the type system in much greater detail, but this one will alert you to some of the surprises that it has in store. Item 1: Understand the Relationship Between TypeScript and JavaScript If you use TypeScript for long, you’ll inevitably hear the phrase “TypeScript is a superset of JavaScript” or “TypeScript is a typed superset of JavaScript.” But what does this mean, exactly? And what is the relationship between TypeScript and JavaScript? Since these languages are so closely linked, a strong understanding of how they relate to each is the foundation for using TypeScript well. TypeScript is a superset of JavaScript in a syntactic sense: so long as your JavaScript program doesn’t have any syntax errors then it is also a TypeScript program. It’s quite likely that TypeScript’s type checker will flag some issues with your code. But this is 1
an independent problem. TypeScript will still parse your code and emit JavaScript. (This is another key part of the relationship. We’ll explore this more in Item 3.) TypeScript files use a .ts (or .tsx) extension, rather than the .js (or .jsx) extension of a JavaScript file. This doesn’t mean that TypeScript is a completely different language! Since TypeScript is a superset of JavaScript, the code in your .js files is already Type‐ Script. Renaming main.js to main.ts doesn’t change that. This is enormously helpful if you’re migrating an existing JavaScript codebase to TypeScript. It means that you don’t have to rewrite any of your code in another lan‐ guage to start using TypeScript and get the benefits it provides. This would not be true if you chose to rewrite your JavaScript in a language like Java. This gentle migra‐ tion path is one of the best features of TypeScript. There will be much more to say about this topic in Chapter 8. All JavaScript programs are TypeScript programs, but the converse is not true: there are TypeScript programs which are not JavaScript programs. This is because Type‐ Script adds additional syntax for specifying types. (There are some other bits of syn‐ tax it adds, largely for historical reasons. See Item 53.) For instance, this is a valid TypeScript program: function greet(who: string) { console.log('Hello', who); } But when you run this through a program like node that expects JavaScript, you’ll get an error: function greet(who: string) { ^ SyntaxError: Unexpected token : The : string is a type annotation that is specific to TypeScript. Once you use one, you’ve gone beyond plain JavaScript (see Figure 1-1). Figure 1-1. All JavaScript is TypeScript, but not all TypeScript is JavaScript 2 | Chapter 1: Getting to Know TypeScript
The above is a preview of the first 20 pages. Register to read the complete e-book.