Statistics
309
Views
139
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2025-08-02

AuthorJosh Goldberg

TypeScript has conquered the world of JavaScript: it's one of the world's fastest growing and most popular languages across developer surveys, widely used in consumer and business companies alike, and frequently credited for helping massive web applications scale. But what is TypeScript? How does it work, why does it work, and how can we use it? Learning TypeScript takes beginner to intermediate JavaScript programmers from knowing nothing about "types" or a "type system" to full mastery of the fundamentals of TypeScript. It's more than a means to find bugs and typosit's a useful system for declaring the way our JavaScript should work and helping us stick to it. You'll learn how TypeScript: • interacts with JavaScript • analyzes and understands code • augments your existing development pattern • helps you document your code • works with IDEs to provide refactoring tools • assists local development in refactoring code • helps you develop more quickly with fewer bugs

Tags
javascripttypescript
ISBN: 1098110307
Publisher: O'Reilly Media, Inc.
Publish Year: 2022
Language: 中文
Pages: 320
File Format: PDF
File Size: 5.2 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.

Lea rning Typ eScrip t Lea rning Typ eScrip t Josh Goldberg Learning TypeScript Enhance Your Web Development Skills Using Type-Safe JavaScript
WEB PL ATFORM “Learning TypeScript is an excellent, approachable resource. Josh introduces the key parts of TypeScript without getting bogged down by unnecessary details.” —Ryan Cavanaugh Principal Software Engineering Manager, Microsoft; Development Lead, TypeScript “Josh’s expertise bursts through the pages of Learning TypeScript. The content is not only deeply educational, but fun and compelling as well.” —Cassidy Williams Developer Experience Engineer, Startup Advisor, and Investor Learning TypeScript US $49.99 CAN $62.99 ISBN: 978-1-098-11033-8 Twitter: @oreillymedia linkedin.com/company/oreilly-media youtube.com/oreillymedia TypeScript has conquered the world of JavaScript. Identified in developer surveys as one of the world’s fastest growing and most popular languages, TypeScript is widely used in consumer and business companies across the world and is frequently credited with helping massive web applications scale. But what exactly is TypeScript? How and why does it work, and how can we use it? This practical book takes beginner and advanced JavaScript programmers alike from knowing nothing about “types” or “type systems” to full mastery of TypeScript fundamentals. You’ll learn: • Benefits of TypeScript and general characteristics of its type system on top of “vanilla” JavaScript • How to inform TypeScript’s type system with development- only type annotations • How TypeScript analyzes and understands code to help you augment your existing development patterns • How TypeScript helps you work with arrays, classes, functions, objects, and other important built-in JavaScript constructs • How to effectively use the plethora of TypeScript configuration options to tailor the TypeScript compiler to your teams and projects • A variety of IDE integrations such as automated refactors and intelligent code searches provided by TypeScript to help you develop quickly with fewer bugs Josh Goldberg is an open source maintainer and software consultant who contributes to TypeScript and the projects in its ecosystem, such as typescript-eslint and TypeStat. Previously, Josh was a staff frontend developer on the web platform team at Codecademy, where he spearheaded the company’s usage of TypeScript and helped create its Learn TypeScript course.
Praise for Learning TypeScript If you ever screamed back at red squiggly lines in your code, then go read Learning TypeScript. Goldberg masterfully puts everything in context while staying practical, showing us that TypeScript is never a restriction, but a valuable asset. —Stefan Baumgartner, senior product architect, Dynatrace; founder, oida.dev Josh puts TypeScript’s most important concepts front and center, and explains them with clear examples and a touch of humor. A must-read for the JavaScript author who wants to write TypeScript like a pro. —Andrew Branch, software engineer on TypeScript, Microsoft Learning TypeScript is an excellent resource for programmers who have coded at least a little before, but may have shied away from typed languages. It goes a level deeper than the TypeScript handbook to give you confidence in using TypeScript in your own projects. —Boris Cherny, software engineer, Meta; author, Programming TypeScript We don’t know what types code is but we’re very proud of Josh and are sure it will be a lovely book. —Frances and Mark Goldberg Josh is that rare individual who is passionate about both acquiring a deep command of the fundamentals and explaining concepts to beginners. I think this book will quickly become a canonical resource for TypeScript novices and experts alike. —Beyang Liu, CTO and cofounder, Sourcegraph
Learning TypeScript is a fantastic introduction and reference to the TS language. Josh’s writing is clear and informative, and that helps with explaining often-confusing TS concepts and syntax. It’s a great place to start for anyone new to TypeScript! —Mark Erikson, senior frontend engineer, Replay; maintainer, Redux Learning TypeScript is a great book to start your TypeScript journey. It gives you the tools to understand the language, the type system, and the IDE integration, and how to use all these to get the most out of your TypeScript experience. —Titian Cernicova Dragomir, software engineer, Bloomberg LP Josh has been a critical part of the TypeScript community for many years, and I’m really excited for folks to be able to benefit from his deep understanding and accessible teaching style through Learning TypeScript. —James Henry, consultant architect, Nrwl; 4x Microsoft MVP; creator, angular-eslint and typescript-eslint Josh is not just a very talented software engineer: he is also an excellent mentor; you can feel his passion for education throughout this book. Learning TypeScript is structured masterfully, and it contains practical, real-world examples that will take TypeScript newbies and enthusiasts to the next level. I can confidently say that Learning TypeScript is the definitive guide for anyone looking to learn or improve their knowledge about TypeScript. —Remo Jansen, CEO, Wolk Software In Learning TypeScript, Josh Goldberg breaks down TypeScript’s most complex concepts into calm, straightforward descriptions and digestible examples that are sure to serve as a learning aid and reference for years to come. From the first haiku to the last joke, Learning TypeScript is a wonderful introduction to the language that’s just my type. No pun intended. —Nick Nisi, staff engineer, C2FO They used to say, “Always bet on JavaScript.” Now it’s, “Always bet on TypeScript,” and this book will be the industry’s most recommended resource. Guaranteed. —Joe Previte, open source TypeScript engineer
Reading Learning TypeScript is like spending time with a warm and smart friend who delights in telling you fascinating things. You’ll walk away entertained and educated about TypeScript whether you knew a lot or a little beforehand. —John Reilly, group principal engineer, Investec; maintainer, ts-loader; Definitely Typed historian Learning TypeScript is a comprehensive yet approachable guide to the TypeScript language and ecosystem. It covers the broad feature set of TypeScript while providing suggestions and explaining trade-offs based on broad experience. —Daniel Rosenwasser, program manager, TypeScript, Microsoft; TC39 representative This is my favorite resource for learning TypeScript. From introductory to advanced topics, it’s all clear, concise, and comprehensive. I found Josh to be an excellent—and fun—writer. —Loren Sands-Ramshaw, author, The GraphQL Guide; TypeScript SDK engineer, Temporal If you are looking to be an effective TypeScript developer, Learning TypeScript has you covered all the way from beginning to advanced concepts. —Basarat Ali Syed, principal engineer, SEEK; author, Beginning NodeJS and TypeScript Deep Dive; Youtuber (Basarat Codes); Microsoft MVP This book is a great way to learn the language and a perfect complement to the TypeScript Handbook. —Orta Therox, ex-TypeScript compiler engineer, Puzmo Josh is one of the clearest and most dedicated TypeScript communicators in the world, and his knowledge is finally in book form! Beginners and experienced devs alike will love the careful curation and sequencing of topics. The tips, notes, and warnings in the classic O’Reilly style are worth their weight in gold. —Shawn “swyx” Wang, head of DX, Airbyte
This book will truly help you learn TypeScript. The theory chapters together with the practice projects strike a good learning balance and cover just about every aspect of the language. Reviewing this book even taught this old dog some new tricks. I finally understand the subtleties of Declaration Files. Highly recommended. —Lenz Weber-Tronic, full stack developer, Mayflower Germany; maintainer, Redux Learning TypeScript is an accessible, engaging book that distills Josh’s years of experience developing a TypeScript curriculum to teach you everything you need to know in just the right order. Whatever your programming background, you’re in good hands with Josh and Learning TypeScript. —Dan Vanderkam, senior staff software engineer, Google; author, Effective TypeScript Learning TypeScript is the book I wish I had when I first got into TypeScript. Josh’s passion for teaching new users oozes from every page. It’s thoughtfully organized into easily digestible chunks, and it covers everything you need to become a TypeScript expert. —Brad Zacher, software engineer, Meta; core maintainer, typescript-eslint
Josh Goldberg Learning TypeScript Enhance Your Web Development Skills Using Type-Safe JavaScript Boston Farnham Sebastopol TokyoBeijing
978-1-098-11033-8 [LSI] Learning TypeScript by Josh Goldberg Copyright © 2022 Josh Goldberg. 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: Rita Fernando Production Editor: Clare Jensen Copyeditor: Piper Editorial Consulting LLC Proofreader: nSight, Inc. Indexer: nSight, Inc. Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea June 2022: First Edition Revision History for the First Edition 2022-06-03: First Release 2022-07-01: Second Release See http://oreilly.com/catalog/errata.csp?isbn=9781098110338 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning 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.
This book is dedicated to my incredible partner, Mariah, who introduced me to the joy of adopting backyard cats and has regretted it ever since. Toot.
(This page has no text content)
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Part I. Concepts 1. From JavaScript to TypeScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 History of JavaScript 3 Vanilla JavaScript’s Pitfalls 4 Costly Freedom 4 Loose Documentation 4 Weaker Developer Tooling 5 TypeScript! 6 Getting Started in the TypeScript Playground 6 TypeScript in Action 6 Freedom Through Restriction 7 Precise Documentation 8 Stronger Developer Tooling 8 Compiling Syntax 10 Getting Started Locally 10 Running Locally 11 Editor Features 12 What TypeScript Is Not 12 A Remedy for Bad Code 12 Extensions to JavaScript (Mostly) 13 Slower Than JavaScript 13 Finished Evolving 14 Summary 14 ix
2. The Type System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 What’s in a Type? 17 Type Systems 19 Kinds of Errors 20 Assignability 21 Understanding Assignability Errors 21 Type Annotations 22 Unnecessary Type Annotations 23 Type Shapes 24 Modules 25 Summary 27 3. Unions and Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Union Types 29 Declaring Union Types 30 Union Properties 30 Narrowing 31 Assignment Narrowing 31 Conditional Checks 32 Typeof Checks 33 Literal Types 33 Literal Assignability 35 Strict Null Checking 36 The Billion-Dollar Mistake 36 Truthiness Narrowing 37 Variables Without Initial Values 38 Type Aliases 39 Type Aliases Are Not JavaScript 39 Combining Type Aliases 40 Summary 40 4. Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Object Types 43 Declaring Object Types 44 Aliased Object Types 45 Structural Typing 45 Usage Checking 46 Excess Property Checking 47 Nested Object Types 48 Optional Properties 50 Unions of Object Types 51 Inferred Object-Type Unions 51 x | Table of Contents
Explicit Object-Type Unions 52 Narrowing Object Types 53 Discriminated Unions 53 Intersection Types 54 Dangers of Intersection Types 55 Summary 57 Part II. Features 5. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Function Parameters 61 Required Parameters 62 Optional Parameters 63 Default Parameters 64 Rest Parameters 64 Return Types 65 Explicit Return Types 66 Function Types 67 Function Type Parentheses 68 Parameter Type Inferences 69 Function Type Aliases 69 More Return Types 70 Void Returns 70 Never Returns 72 Function Overloads 72 Call-Signature Compatibility 73 Summary 74 6. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Array Types 76 Array and Function Types 76 Union-Type Arrays 76 Evolving Any Arrays 77 Multidimensional Arrays 78 Array Members 78 Caveat: Unsound Members 79 Spreads and Rests 79 Spreads 79 Spreading Rest Parameters 80 Tuples 80 Tuple Assignability 81 Table of Contents | xi
Tuple Inferences 83 Summary 85 7. Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Type Aliases Versus Interfaces 87 Types of Properties 89 Optional Properties 89 Read-Only Properties 90 Functions and Methods 91 Call Signatures 92 Index Signatures 93 Nested Interfaces 96 Interface Extensions 97 Overridden Properties 98 Extending Multiple Interfaces 99 Interface Merging 99 Member Naming Conflicts 100 Summary 101 8. Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Class Methods 103 Class Properties 104 Function Properties 105 Initialization Checking 106 Optional Properties 108 Read-Only Properties 108 Classes as Types 109 Classes and Interfaces 111 Implementing Multiple Interfaces 112 Extending a Class 114 Extension Assignability 114 Overridden Constructors 116 Overridden Methods 117 Overridden Properties 118 Abstract Classes 119 Member Visibility 120 Static Field Modifiers 122 Summary 123 9. Type Modifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Top Types 125 any, Again 125 xii | Table of Contents
unknown 126 Type Predicates 127 Type Operators 129 keyof 129 typeof 131 Type Assertions 132 Asserting Caught Error Types 133 Non-Null Assertions 134 Type Assertion Caveats 135 Const Assertions 137 Literals to Primitives 137 Read-Only Objects 139 Summary 140 10. Generics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 Generic Functions 142 Explicit Generic Call Types 143 Multiple Function Type Parameters 144 Generic Interfaces 145 Inferred Generic Interface Types 146 Generic Classes 147 Explicit Generic Class Types 148 Extending Generic Classes 149 Implementing Generic Interfaces 150 Method Generics 151 Static Class Generics 152 Generic Type Aliases 152 Generic Discriminated Unions 153 Generic Modifiers 154 Generic Defaults 154 Constrained Generic Types 155 keyof and Constrained Type Parameters 156 Promises 157 Creating Promises 157 Async Functions 158 Using Generics Right 159 The Golden Rule of Generics 159 Generic Naming Conventions 160 Summary 161 Table of Contents | xiii
Part III. Usage 11. Declaration Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Declaration Files 165 Declaring Runtime Values 166 Global Values 168 Global Interface Merging 168 Global Augmentations 169 Built-In Declarations 170 Library Declarations 170 DOM Declarations 172 Module Declarations 173 Wildcard Module Declarations 174 Package Types 174 declaration 174 Dependency Package Types 175 Exposing Package Types 176 DefinitelyTyped 177 Type Availability 178 Summary 179 12. Using IDE Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Navigating Code 182 Finding Definitions 183 Finding References 184 Finding Implementations 185 Writing Code 186 Completing Names 186 Automatic Import Updates 187 Code Actions 188 Working Effectively with Errors 191 Language Service Errors 192 Summary 197 13. Configuration Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 tsc Options 199 Pretty Mode 200 Watch Mode 200 TSConfig Files 201 tsc --init 202 CLI Versus Configuration 202 File Inclusions 203 xiv | Table of Contents
include 203 exclude 204 Alternative Extensions 204 JSX Syntax 204 resolveJsonModule 206 Emit 207 outDir 207 target 208 Emitting Declarations 209 Source Maps 210 noEmit 212 Type Checking 212 lib 212 skipLibCheck 213 Strict Mode 213 Modules 218 module 219 moduleResolution 219 Interoperability with CommonJS 220 isolatedModules 221 JavaScript 222 allowJs 222 checkJs 223 JSDoc Support 224 Configuration Extensions 225 extends 225 Configuration Bases 227 Project References 227 composite 228 references 229 Build Mode 229 Summary 231 Part IV. Extra Credit 14. Syntax Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Class Parameter Properties 236 Experimental Decorators 238 Enums 239 Automatic Numeric Values 241 String-Valued Enums 242 Table of Contents | xv
Const Enums 243 Namespaces 244 Namespace Exports 245 Nested Namespaces 247 Namespaces in Type Definitions 248 Prefer Modules Over Namespaces 248 Type-Only Imports and Exports 249 Summary 251 15. Type Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Mapped Types 253 Mapped Types from Types 254 Changing Modifiers 256 Generic Mapped Types 258 Conditional Types 259 Generic Conditional Types 260 Type Distributivity 261 Inferred Types 262 Mapped Conditional Types 263 never 263 never and Intersections and Unions 263 never and Conditional Types 264 never and Mapped Types 264 Template Literal Types 265 Intrinsic String Manipulation Types 267 Template Literal Keys 267 Remapping Mapped Type Keys 268 Type Operations and Complexity 270 Summary 271 Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 xvi | Table of Contents
Preface My journey to TypeScript was not a direct or quick one. I started off in school primarily writing Java, then C++, and like many new developers raised on statically typed languages, I looked down on JavaScript as “just” the sloppy little scripting language people throw onto websites. My first substantial project in the language was a silly remake of the original Super Mario Bros. video game in pure HTML5/CSS/JavaScript and, typical of many first projects, was an absolute mess. In the beginning of the project I instinctively disliked JavaScript’s weird flexibility and lack of guardrails. It was only toward the end that I really began to respect JavaScript’s features and quirks: its flexibility as a language, its ability to mix and match small functions, and its ability to just work in user browsers within seconds of page load. By the time I finished that first project, I had fallen in love with JavaScript. Static analysis (tools that analyze your code without running it) such as TypeScript also gave me a queasy gut feeling at first. JavaScript is so breezy and fluid, I thought, why bog ourselves down with rigid structures and types? Were we reverting back to the worlds of Java and C++ that I had left behind? Coming back to my old projects, it took me all of 10 minutes of struggling to read through my old, convoluted JavaScript code to understand how messy things could get without static analysis. The act of cleaning that code up showed me all the places I would have benefited from some structure. From that point on, I was hooked onto adding as much static analysis to my projects as I could. It’s been nearly a decade since I first tinkered with TypeScript, and I enjoy it as much as ever. The language is still evolving with new features and is more useful than ever in providing safety and structure to JavaScript. I hope that by reading Learning TypeScript you can learn to appreciate TypeScript the way I do: not just as a means to find bugs and typos—and certainly not a substantial xvii
change to JavaScript code patterns—but as JavaScript with types: a beautiful system for declaring the way our JavaScript should work, and helping us stick to it. Who Should Read This Book If you have an understanding of writing JavaScript code, can run basic commands in a terminal, and are interested in learning about TypeScript, this book is for you. Maybe you’ve heard TypeScript can help you write a lot of JavaScript with fewer bugs (true!) or document your code well for other people to read (also true!). Maybe you’ve seen TypeScript show up in a lot of job postings, or in a new role you’re starting. Whatever your reason, as long as you come in knowing the fundamentals of Java‐ Script—variables, functions, closures/scope, and classes—this book will take you from no TypeScript knowledge to mastering the fundamentals and most important features of the language. By the end of this book, you will understand: • The history and context for why TypeScript is useful on top of “vanilla” JavaScript • How a type system models code • How a type checker analyzes code • How to use development-only type annotations to inform the type system • How TypeScript works with IDEs (Integrated Development Environments) to provide code exploration and refactoring tools And you will be able to: • Articulate the benefits of TypeScript and general characteristics of its type sys‐ tem. • Add type annotations where useful in your code. • Represent moderately complex types using TypeScript’s built-in inferences and new syntax. • Use TypeScript to assist local development in refactoring code. Why I Wrote This Book TypeScript is a wildly popular language in both industry and open source: • GitHub’s 2021 and 2020 State of the Octoverses have it at the platform’s fourth top language, up from seventh in 2019 and 2018 and tenth in 2017. • StackOverflow’s 2021 Developer Survey has it at the world’s third most loved language (72.73% of users). xviii | Preface