No description
AI Reading Assistant
Summary and highlights from this book's index; jump to passages in the text
Tags
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.
Page
1
(This page has no text content)
Page
2
CONTENTS IN DETAIL FOREWORD INTRODUCTION The Birth of TypeScript Why Now? Who Is This Book For? What We’ll Cover Online Resources The Book’s Exercises @ts-expect-error Vitest PART I: GETTING STARTED 1 KICKSTART YOUR TYPESCRIPT SETUP What’s Different About TypeScript? A High-Level View of How TypeScript Works Tools for TypeScript Development Installing Node.js Installing the pnpm Package Manager Installing TypeScript Summary 2 IDE SUPERPOWERS Autocomplete Manual Autocomplete Exercise 2-1: Autocomplete TypeScript Error Checking Runtime Errors Non-Runtime Errors Warning Locations Multiline Errors Introspecting Variables and Declarations Exercise 2-2: Hovering Over a Function Call
Page
3
JSDoc Comments Exercise 2-3: Adding Documentation for Hovers Navigating with Go to Definition and Go to References Rename Symbol Automatic Imports Quick Fixes Restarting the VS Code Server Working in JavaScript Exercise 2-4: Quick Fix Refactoring Summary 3 TYPESCRIPT IN THE DEVELOPMENT PIPELINE The Problem with TypeScript in the Browser Transpiling TypeScript Initializing a TypeScript Project Running tsc Does TypeScript Change Your JavaScript? A Note on Version Control Running TypeScript in Watch Mode Errors in the TypeScript CLI TypeScript with Modern Frameworks TypeScript as a Linter Summary PART II: FUNDAMENTALS 4 ESSENTIAL TYPES AND ANNOTATIONS Type Annotations The Basic Types Function Parameter Annotations Variable Annotations Type Inference The any Type Exercise 4-1: Basic Types with Function Parameters Exercise 4-2: Annotating Empty Parameters Exercise 4-3: The Basic Types Exercise 4-4: The any Type Object Literal Types Optional Object Properties Exercise 4-5: Object Literal Types Exercise 4-6: Optional Property Types Type Aliases Sharing Types Across Modules Exercise 4-7: The type Keyword
Page
4
Arrays Arrays of Objects Tuples Named Tuples Exercise 4-8: Array Type Exercise 4-9: Arrays of Objects Exercise 4-10: Tuples Exercise 4-11: Optional Members of Tuples Passing Types to Functions Passing Types to Set Not All Functions Can Receive Types Exercise 4-12: Passing Types to Map Exercise 4-13: JSON.parse() Can’t Receive Type Arguments Typing Functions Optional Parameters Default Parameters Function Return Types Rest Parameters Function Types The void Type Async Functions Exercise 4-14: Optional Function Parameters Exercise 4-15: Default Function Parameters Exercise 4-16: Rest Parameters Exercise 4-17: Function Types Exercise 4-18: Functions Returning void Exercise 4-19: void vs. undefined Exercise 4-20: Async Functions Summary 5 UNIONS, LITERALS, AND NARROWING Union Types Declaring Union Types Literal Types Combining Unions with Unions Exercise 5-1: string or null Exercise 5-2: Restricting Function Parameters Wide and Narrow Types Unions Are Wider Than Their Members The Process of Narrowing Exercise 5-3: Narrowing with if Statements Exercise 5-4: Throwing Errors to Narrow Exercise 5-5: Using in to Narrow The unknown and never Types The Widest Type: unknown The Difference Between unknown and any The Narrowest Type: never
Page
5
Exercise 5-6: Narrowing Errors with instanceof Exercise 5-7: Narrowing unknown to a Value Discriminated Unions The Problem: The Bag of Optionals The Solution: Discriminated Unions Exercise 5-8: Destructuring a Discriminated Union Exercise 5-9: Narrowing a Discriminated Union with a switch Statement Exercise 5-10: Discriminated Tuples Exercise 5-11: Handling Defaults with a Discriminated Union Summary PART III: OBJECTS, CLASSES, AND MUTABILITY 6 OBJECTS Extending Objects Intersection Types Interfaces Intersections vs. interface extends Types vs. Interfaces Exercise 6-1: Creating an Intersection Type Exercise 6-2: Extending Interfaces Dynamic Object Keys Index Signatures The Record Type A Combination of Known and Dynamic Keys The PropertyKey Type Exercise 6-3: Using an Index Signature for Dynamic Keys Exercise 6-4: Default Properties with Dynamic Keys Exercise 6-5: Restricting Object Keys with Records Exercise 6-6: Dynamic Key Support Reducing Duplication with Utility Types The Partial Type The Required Type The Pick Type The Omit Type Union Types with Omit and Pick Exercise 6-7: Expecting Certain Properties Exercise 6-8: Updating a Product Summary 7 MUTABILITY Mutability and Inference How TypeScript Infers let
Page
6
How TypeScript Infers const Object Property Inference Readonly Object Properties Exercise 7-1: Inference with an Array of Objects Exercise 7-2: Avoiding Array Mutation Exercise 7-3: An Unsafe Tuple Deep Immutability with as const as const vs. Variable Annotation as const vs. Object.freeze Exercise 7-4: Inferring Literal Values in Arrays Summary 8 CLASSES Creating a Class Adding a Constructor Adding Arguments to the Constructor Using a Class as a Type Properties in Classes Class Property Initializers readonly Class Properties Optional Class Properties public and private Properties Class Methods Class Inheritance Extending a Class protected Properties Safe Overrides with override The implements Keyword Abstract Classes Abstract Methods Exercise 8-1: Creating a Class Exercise 8-2: Implementing Class Methods Exercise 8-3: Implementing a Getter Exercise 8-4: Implementing a Setter Exercise 8-5: Extending a Class Summary 9 TYPESCRIPT-ONLY FEATURES Class Parameter Properties Enums Numeric Enums String Enums Enums Are Strange Should You Use Enums? Namespaces How Namespaces Compile
Page
7
Merging Namespaces Should You Use Namespaces? Type-Only Namespaces When to Use ECMAScript vs. TypeScript The Future of TypeScript: Erasable Syntax Only Summary PART IV: WORKING WITH THE COMPILER 10 DERIVING TYPES Deriving Types from Other Types The keyof Operator The typeof Operator You Can’t Create Values from Types Indexed Access Types Chaining Multiple Indexed Access Types Passing a Union to an Indexed Access Type Getting an Object’s Values with keyof Using as const for JavaScript-Style Enums Enums Require You to Pass the Enum Value Enums Are Nominal Which Approach Should You Use? Exercise 10-1: Reducing Key Repetition Exercise 10-2: Deriving a Type from a Value Exercise 10-3: Accessing Specific Values Exercise 10-4: Unions with Indexed Access Types Exercise 10-5: Extract a Union of All Values Exercise 10-6: Creating a Union from an as const Array Deriving Types from Functions Parameters ReturnType Awaited Why Derive Types from Functions? Exercise 10-7: A Single Source of Truth Exercise 10-8: Typing Based on a Return Value Exercise 10-9: Unwrapping a Promise Transforming Derived Types Exclude NonNullable Extract Deriving vs. Decoupling When Decoupling Makes Sense When Deriving Makes Sense Summary
Page
8
11 ANNOTATIONS AND ASSERTIONS Annotating Variables vs. Values Annotating Values with satisfies Narrowing Values with satisfies Assertions: Forcing the Type of Values The as Assertion The Non-Null Assertion Error Suppression Directives @ts-expect-error @ts-ignore @ts-nocheck Suppressing Errors vs. as any When to Suppress Errors When You Know More Than TypeScript When TypeScript Is Being “Dumb” When You Don’t Understand the Error Exercise 11-1: Providing Additional Info to TypeScript Exercise 11-2: Solving Issues with Assertions Exercise 11-3: Enforcing a Valid Configuration Exercise 11-4: Variable Annotation vs. as vs. satisfies Exercise 11-5: Creating a Deeply Read-Only Object Summary 12 THE WEIRD PARTS The Evolving any Type Excess Property Warnings No Excess Property Checks on Variables No Excess Property Checks When Comparing Functions Open vs. Closed Object Types Fresh and Stale Objects Object Keys Are Loosely Typed The Empty Object Type The Type and Value Worlds Classes Can Cross Between Worlds Enums Can Cross Between Worlds The this Keyword Can Cross Between Worlds Naming Types and Values the Same Using this in Functions Arrow Functions Don’t Support this Function Assignability Unions of Functions Intersect Parameters Exercise 12-1: Accepting Anything Except null and undefined Exercise 12-2: Detecting Excess Properties in an Object Exercise 12-3: Detecting Excess Properties in a Function Exercise 12-4: Iterating over Objects
Page
9
Exercise 12-5: Function Parameter Comparisons Exercise 12-6: Unions of Functions with Object Params Exercise 12-7: Unions of Functions with Incompatible Parameters Summary PART V: UNDERSTANDING THE ENVIRONMENT 13 MODULES, SCRIPTS, AND DECLARATION FILES Understanding Modules and Scripts Modules Have Local Scope Scripts Have Global Scope TypeScript Guesses Which to Use Forcing Modules with moduleDetection Declaration Files Declaration Files Describe JavaScript Declaration Files Can Add to the Global Scope Declaration Files Can’t Contain Implementations The declare Keyword Typing Global Variables Scoping Global Variables to One File More Ways to declare Module Augmentation vs. Module Overriding Declaration Files You Don’t Control TypeScript’s Types DOM Types Types That Ship with Libraries DefinitelyTyped The skipLibCheck Config Option Authoring Declaration Files Should You Store Your Types in Declaration Files? Is Using Global Types a Good Idea? Exercise 13-1: Typing a JavaScript Module Exercise 13-2: Ambient Context Exercise 13-3: Modifying window Exercise 13-4: Modifying process.env Summary 14 CONFIGURING TYPESCRIPT Recommended Configuration Additional Configuration Options The Complete Base Configuration Base Options target
Page
10
esModuleInterop isolatedModules Strictness Options noUncheckedIndexedAccess Other Strictness Options The Two Choices for module NodeNext Preserve noEmit Source Maps Transpiling Code for Library Use outDir Creating Declaration Files Declaration Maps jsx A Note on Node’s TypeScript Support Managing Multiple TypeScript Configurations How TypeScript Finds tsconfig.json Extending Configurations --project Project References Summary PART VI: ADVANCED APPLICATION DEVELOPMENT 15 DESIGNING YOUR TYPES Generic Types Multiple Type Parameters All Type Arguments Must Be Provided Default Type Parameters Type Parameter Constraints Template Literal Types in TypeScript Combining Template Literal Types with Union Types Transforming String Types Conditional Types Mapped Types Key Remapping with as Using Mapped Types with Union Types Exercise 15-1: Creating a DataShape Type Helper Exercise 15-2: Typing PromiseFunc Exercise 15-3: Working with the Result Type Exercise 15-4: Constraining the Result Type Exercise 15-5: A Stricter Omit Type
Page
11
Exercise 15-6: Route Matching Exercise 15-7: Sandwich Permutations Exercise 15-8: Attribute Getters Exercise 15-9: Renaming Keys in a Mapped Type Summary 16 BUILDING POWERFUL SHARED UTILITIES Generic Functions Generic Function Type Alias vs. Generic Type Missing or Conflicting Type Arguments There Is No Such Thing as a “Generic” The Problem Generic Functions Solve Debugging the Inferred Type of Generic Functions Type Parameter Defaults Constraining Type Parameters Type Predicates Assertion Functions Function Overloads The Implementation Signature Function Overloads vs. Unions Exercise 16-1: Making a Function Generic Exercise 16-2: Default Type Arguments Exercise 16-3: Inference in Generic Functions Exercise 16-4: Type Parameter Constraints Exercise 16-5: Combining Generic Types and Functions Exercise 16-6: Multiple Type Arguments in a Generic Function Exercise 16-7: Assertion Functions Summary INDEX
Page
12
TOTAL TYPESCRIPT The Essentials by Matt Pocock with Taylor Bell San Francisco
Page
13
TOTAL TYPESCRIPT. Copyright © 2026 by Matt Pocock with Taylor Bell. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. First printing 30 29 28 27 26 1 2 3 4 5 ISBN-13: 978-1-7185-0416-5 (print) ISBN-13: 978-1-7185-0417-2 (ebook) Published by No Starch Press®, Inc. 245 8th Street, San Francisco, CA 94103 phone: +1.415.863.9900 www.nostarch.com; info@nostarch.com Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Sabrina Plomitallo-González Production Editor: Sydney Cromwell Developmental Editor: Jill Franklin Cover Illustrator: Rob Fiore Interior Design: Octopod Studios Technical Reviewer: Titian Cernicova-Dragomir Copyeditor: Kim Wimpsett Proofreader: Audrey Doyle Indexer: BIM Creatives, LLC Library of Congress Cataloging-in-Publication Data Names: Pocock, Matt author | Bell, Taylor, (Computer science researcher) author Title: Total Typescript / by Matt Pocock with Taylor Bell. Description: San Francisco, CA : No Starch Press, [2026] | Includes index. Identifiers: LCCN 2025048382 (print) | LCCN 2025048383 (ebook) | ISBN 9781718504165 print | ISBN 9781718504172 ebook Subjects: LCSH: TypeScript (Computer program language) Classification: LCC QA76.73.T97 P63 2026 (print) | LCC QA76.73.T97 (ebook) LC record available at https://lccn.loc.gov/2025048382 LC ebook record available at https://lccn.loc.gov/2025048383 For customer service inquiries, please contact info@nostarch.com. For information on distribution, bulk sales, corporate sales, or translations: sales@nostarch.com. For permission to translate this work: rights@nostarch.com. To report counterfeit copies or piracy: counterfeit@nostarch.com. The authorized representative in the EU for product safety and compliance is EU Compliance Partner, Pärnu mnt. 139b-14, 11317 Tallinn, Estonia, hello@eucompliancepartner.com, +3375690241.
Page
14
No Starch Press and the No Starch Press iron logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
Page
15
For Louise and Isaac
Page
16
About the Authors Matt Pocock is a full-time TypeScript educator, having worked as a developer and educator for Vercel and Stately.ai. He teaches TypeScript workshops, builds online courses, and watches horses gallop by his office in Oxfordshire, England. Taylor Bell has worked as a technical copywriter, researcher, developer, and associated roles in between. He studied communication theory and computer science at Boise State University in his hometown of Boise, Idaho. About the Technical Reviewer Titian Cernicova-Dragomir is a developer on the JavaScript infrastructure team at Bloomberg, where he works on JavaScript and TypeScript tooling for internal developers. He’s passionate about TypeScript and is an active member of the TypeScript community on Stack Overflow. Cernicova- Dragomir is also a TypeScript compiler contributor and recently contributed the implementation of ES class private methods and private static members.
Page
17
FOREWORD In early 2012, I joined a small team of engineers at Microsoft that was tasked with improving the JavaScript development experience for projects across the company. The concept was simple: Create a language, based on JavaScript, that added gradual static typing, and use that static typing to empower developers to code more quickly, more confidently, and more accurately. At the time, static typing was out of fashion among most JavaScript developers. I figured that if we did a fantastic job, we might eventually gain mindshare among 20 percent of developers, maybe a little more in larger projects. Our initial release was met with guarded skepticism. Was Microsoft really turning over a new leaf and embracing open source? Could TypeScript find a way to describe the behavior of all our favorite libraries? Wasn’t the chaos of JavaScript half the fun of using it? At the same time, we saw a tremendous enthusiasm start to form. TypeScript was the solution that so many people had been looking for. They saw great potential in the project and realized what it might eventually be able to deliver. A vibrant community of developers, content creators, authors, and commentators began to form. Thirteen years later, TypeScript has become the de facto standard for writing modern JavaScript, with virtually 100 percent adoption in large projects and three quarters of JavaScript developers using TypeScript for most if not all of their code. It’s been an incredible journey to see TypeScript grow from a small moonshot project to a truly dominant player in the language space. The community has expanded alongside this growth. Much like I never believed we’d have a majority share of JavaScript developers, I’ve been
Page
18
pleasantly surprised to see the incredible network of TypeScript educators, influencers, and creators grow around our project. I’ve always been so energized by that community. TypeScript would not be where it is today without the intelligent, engaged, and thoughtful contributions from so many different people from around the world. We stand not just on the shoulders of giants but on a foundation of thousands of experts and enthusiasts who want to make JavaScript development a better experience. Matt Pocock in particular stands out for his tireless work to explain TypeScript. His focus on approachable, comprehensive, and pragmatic TypeScript education has been an invaluable resource to countless developers. This book takes that work to the next level, providing a clear and concise overview of the language. What I’ve always appreciated about Matt’s work as a technical writer is that he’s unafraid to stake out an opinion and consistently displays good taste. (In other words, he tends to agree with me!) TypeScript development offers a huge amount of flexibility, and using the language effectively is as much art as science. As an exercise for the reader, I offer you an additional challenge: As you read the book, think about the trade-offs we make every time we write a line of code. Do we want to be explicit or concise? Are error cases handled immediately or deferred? How do we balance the precision of types we write against the complexity of those types? The text of the book offers excellent guidance in these matters, often more implicitly than explicitly. Test yourself for mastery of these concepts by seeing if you can realize alternative solutions to the tasks here that vary on these axes. My hope is that you take away from this book not just an understanding of TypeScript as a language but also a feel for its community. The way we balance safety, flexibility, structure, creativity, and so much more is one of the things that make the language such an expressive joy to work with. Happy coding! Ryan Cavanaugh Development Lead for the TypeScript Team at Microsoft Seattle, Washington
Page
19
INTRODUCTION If you were building JavaScript apps in the 2000s, you were probably having a bad time. Users were demanding more interactive experiences on the web. Developers were building large, complex web apps. And JavaScript, the language of the web, began to creak under the strain. Back then, the experience of writing JavaScript was not particularly fun. Editor features that are now commonplace, like autocomplete and error highlighting, often weren’t available. As applications grew more and more complex, working with JavaScript became a nightmare. This came to a head at Microsoft, where our story starts. The Birth of TypeScript Around 2010, Microsoft noticed something strange. Some of its teams were using a community project called Script# (ScriptSharp) to build JavaScript apps. The Script# library allowed for developers to write code in C#, which would then be transformed into JavaScript. There are a lot of benefits to writing code in a strongly typed language like C#. When you make silly errors like misspelling a variable name, you’ll get a warning right away instead of finding out when the build doesn’t work. More importantly, refactoring code in a strongly typed language is much simpler. If you needed to change how a function was called, this could be done in a few clicks instead of a few hours. By comparison, writing in JavaScript felt like carving your code in stone tablets. Once written, it was hard to change.
Page
20
Microsoft tasked Anders Hejlsberg, the creator of C#, with investigating Script#. He was surprised to find that people were so annoyed with JavaScript that they were willing to code in a completely different language to avoid it. However, he found the combination of C# and the Script# library bizarre. Wouldn’t it make more sense to create a new language that was closer to JavaScript and enabled developers to use all the IDE features that JavaScript was missing? And so, TypeScript was born. In the decade or so since its introduction, TypeScript has become a staple of modern development. It’s been adopted by huge companies like Google, Netflix, and Airbnb. Teams that use TypeScript ship better software at greater speed—and are happier as a result. Why Now? We are in a moment of enormous change, both for developers and for TypeScript. For developers, artificial intelligence is revolutionizing the way we work. AI is finding a home in our IDEs, helping us write code faster than ever. But one thing is clear: Without good feedback loops, AI can quickly lose its way. This makes TypeScript, which provides a fast feedback loop inside the IDE, a natural fit for AI-driven development. Most IDEs are already utilizing TypeScript’s error checking to improve their AI agents, and I feel this space is still underexplored. But TypeScript itself is in flux. In 2025, the TypeScript team announced it was porting TypeScript’s type checker to Go, promising a 10× speedup for autocomplete, in-IDE errors, and project type checking. A faster TypeScript means faster feedback loops, especially in large projects. And it has TypeScript developers extremely excited. Learning TypeScript has rarely been more appealing. You’ll be coding in a language that AI loves to use. You’ll ship better code, faster than before. Learning TypeScript totally changed my career. I hope it will do the same for you.
Loading comments...
Reply to Comment
Edit Comment