Total Typescript - The Essentials

Total Typescript - The Essentials

Total Typescript - The Essentials
Автор: Bell Taylor, Pocock Matt
Дата выхода: 2026
Издательство: No Starch Press, Inc.
Количество страниц: 545
Размер файла: 1,8 МБ
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы

Title Page....12

Copyright....13

Dedication....15

About the Authors and the Technical Reviewers....16

Foreword....17

Introduction....19

The Birth of TypeScript....19

Why Now?....20

Who Is This Book For?....21

What We’ll Cover....21

Online Resources....23

The Book’s Exercises....23

@ts-expect-error....24

Vitest....24

Part I: Getting Started....26

1. Kickstart Your Typescript Setup....27

What’s Different About TypeScript?....27

A High-Level View of How TypeScript Works....28

Tools for TypeScript Development....29

Installing Node.js....30

Installing the pnpm Package Manager....30

Installing TypeScript....31

Summary....32

2. Ide Superpowers....33

Autocomplete....33

Manual Autocomplete....34

Exercise 2-1: Autocomplete....34

TypeScript Error Checking....35

Runtime Errors....36

Non-Runtime Errors....36

Warning Locations....37

Multiline Errors....38

Introspecting Variables and Declarations....39

Exercise 2-2: Hovering Over a Function Call....40

JSDoc Comments....42

Exercise 2-3: Adding Documentation for Hovers....43

Navigating with Go to Definition and Go to References....44

Rename Symbol....45

Automatic Imports....45

Quick Fixes....46

Restarting the VS Code Server....46

Working in JavaScript....47

Exercise 2-4: Quick Fix Refactoring....47

Summary....50

3. Typescript in the Development Pipeline....51

The Problem with TypeScript in the Browser....51

Transpiling TypeScript....53

Initializing a TypeScript Project....53

Running tsc....54

Does TypeScript Change Your JavaScript?....55

A Note on Version Control....56

Running TypeScript in Watch Mode....56

Errors in the TypeScript CLI....56

TypeScript with Modern Frameworks....57

TypeScript as a Linter....58

Summary....58

Part II: Fundamentals....60

4. Essential Types and Annotations....61

Type Annotations....61

The Basic Types....61

Function Parameter Annotations....62

Variable Annotations....63

Type Inference....64

The any Type....66

Exercise 4-1: Basic Types with Function Parameters....67

Exercise 4-2: Annotating Empty Parameters....69

Exercise 4-3: The Basic Types....70

Exercise 4-4: The any Type....72

Object Literal Types....74

Optional Object Properties....74

Exercise 4-5: Object Literal Types....75

Exercise 4-6: Optional Property Types....77

Type Aliases....78

Sharing Types Across Modules....79

Exercise 4-7: The type Keyword....80

Arrays....82

Arrays of Objects....83

Tuples....84

Named Tuples....84

Exercise 4-8: Array Type....85

Exercise 4-9: Arrays of Objects....86

Exercise 4-10: Tuples....89

Exercise 4-11: Optional Members of Tuples....90

Passing Types to Functions....92

Passing Types to Set....92

Not All Functions Can Receive Types....93

Exercise 4-12: Passing Types to Map....95

Exercise 4-13: JSON.parse() Can’t Receive Type Arguments....96

Typing Functions....99

Optional Parameters....99

Default Parameters....99

Function Return Types....100

Rest Parameters....101

Function Types....102

The void Type....103

Async Functions....104

Exercise 4-14: Optional Function Parameters....105

Exercise 4-15: Default Function Parameters....106

Exercise 4-16: Rest Parameters....108

Exercise 4-17: Function Types....109

Exercise 4-18: Functions Returning void....112

Exercise 4-19: void vs. undefined....114

Exercise 4-20: Async Functions....115

Summary....118

5. Unions, Literals, and Narrowing....120

Union Types....120

Declaring Union Types....121

Literal Types....122

Combining Unions with Unions....122

Exercise 5-1: string or null....123

Exercise 5-2: Restricting Function Parameters....125

Wide and Narrow Types....126

Unions Are Wider Than Their Members....127

The Process of Narrowing....129

Exercise 5-3: Narrowing with if Statements....130

Exercise 5-4: Throwing Errors to Narrow....133

Exercise 5-5: Using in to Narrow....135

The unknown and never Types....138

The Widest Type: unknown....138

The Difference Between unknown and any....139

The Narrowest Type: never....140

Exercise 5-6: Narrowing Errors with instanceof....142

Exercise 5-7: Narrowing unknown to a Value....144

Discriminated Unions....147

The Problem: The Bag of Optionals....148

The Solution: Discriminated Unions....149

Exercise 5-8: Destructuring a Discriminated Union....151

Exercise 5-9: Narrowing a Discriminated Union with a switch Statement....154

Exercise 5-10: Discriminated Tuples....156

Exercise 5-11: Handling Defaults with a Discriminated Union....158

Summary....162

Part III: Objects, Classes, and Mutability....163

6. Objects....164

Extending Objects....164

Intersection Types....165

Interfaces....167

Intersections vs. interface extends....169

Types vs. Interfaces....170

Exercise 6-1: Creating an Intersection Type....172

Exercise 6-2: Extending Interfaces....174

Dynamic Object Keys....176

Index Signatures....177

The Record Type....178

A Combination of Known and Dynamic Keys....179

The PropertyKey Type....181

Exercise 6-3: Using an Index Signature for Dynamic Keys....181

Exercise 6-4: Default Properties with Dynamic Keys....182

Exercise 6-5: Restricting Object Keys with Records....184

Exercise 6-6: Dynamic Key Support....186

Reducing Duplication with Utility Types....188

The Partial Type....188

The Required Type....189

The Pick Type....191

The Omit Type....191

Union Types with Omit and Pick....193

Exercise 6-7: Expecting Certain Properties....196

Exercise 6-8: Updating a Product....198

Summary....200

7. Mutability....202

Mutability and Inference....202

How TypeScript Infers let....202

How TypeScript Infers const....203

Object Property Inference....204

Readonly Object Properties....207

Exercise 7-1: Inference with an Array of Objects....212

Exercise 7-2: Avoiding Array Mutation....214

Exercise 7-3: An Unsafe Tuple....215

Deep Immutability with as const....217

as const vs. Variable Annotation....218

as const vs. Object.freeze....219

Exercise 7-4: Inferring Literal Values in Arrays....222

Summary....226

8. Classes....227

Creating a Class....227

Adding a Constructor....228

Adding Arguments to the Constructor....229

Using a Class as a Type....230

Properties in Classes....231

Class Property Initializers....231

readonly Class Properties....232

Optional Class Properties....232

public and private Properties....233

Class Methods....235

Class Inheritance....237

Extending a Class....237

protected Properties....239

Safe Overrides with override....240

The implements Keyword....241

Abstract Classes....243

Abstract Methods....245

Exercise 8-1: Creating a Class....246

Exercise 8-2: Implementing Class Methods....247

Exercise 8-3: Implementing a Getter....249

Exercise 8-4: Implementing a Setter....251

Exercise 8-5: Extending a Class....252

Summary....254

9. Typescript-Only Features....255

Class Parameter Properties....255

Enums....256

Numeric Enums....256

String Enums....258

Enums Are Strange....258

Should You Use Enums?....263

Namespaces....263

How Namespaces Compile....265

Merging Namespaces....266

Should You Use Namespaces?....268

Type-Only Namespaces....268

When to Use ECMAScript vs. TypeScript....268

The Future of TypeScript: Erasable Syntax Only....269

Summary....270

Part IV: Working With the Compiler....271

10. Deriving Types....272

Deriving Types from Other Types....272

The keyof Operator....274

The typeof Operator....275

You Can’t Create Values from Types....277

Indexed Access Types....277

Chaining Multiple Indexed Access Types....279

Passing a Union to an Indexed Access Type....279

Getting an Object’s Values with keyof....280

Using as const for JavaScript-Style Enums....280

Enums Require You to Pass the Enum Value....281

Enums Are Nominal....281

Which Approach Should You Use?....283

Exercise 10-1: Reducing Key Repetition....283

Exercise 10-2: Deriving a Type from a Value....285

Exercise 10-3: Accessing Specific Values....286

Exercise 10-4: Unions with Indexed Access Types....287

Exercise 10-5: Extract a Union of All Values....288

Exercise 10-6: Creating a Union from an as const Array....290

Deriving Types from Functions....292

Parameters....292

ReturnType....293

Awaited....294

Why Derive Types from Functions?....294

Exercise 10-7: A Single Source of Truth....296

Exercise 10-8: Typing Based on a Return Value....298

Exercise 10-9: Unwrapping a Promise....300

Transforming Derived Types....301

Exclude....301

NonNullable....302

Extract....303

Deriving vs. Decoupling....304

When Decoupling Makes Sense....304

When Deriving Makes Sense....306

Summary....307

11. Annotations and Assertions....309

Annotating Variables vs. Values....309

Annotating Values with satisfies....312

Narrowing Values with satisfies....313

Assertions: Forcing the Type of Values....314

The as Assertion....314

The Non-Null Assertion....317

Error Suppression Directives....319

@ts-expect-error....319

@ts-ignore....320

@ts-nocheck....321

Suppressing Errors vs. as any....321

When to Suppress Errors....322

When You Know More Than TypeScript....322

When TypeScript Is Being “Dumb”....323

When You Don’t Understand the Error....324

Exercise 11-1: Providing Additional Info to TypeScript....325

Exercise 11-2: Solving Issues with Assertions....327

Exercise 11-3: Enforcing a Valid Configuration....330

Exercise 11-4: Variable Annotation vs. as vs. satisfies....332

Exercise 11-5: Creating a Deeply Read-Only Object....338

Summary....340

12. The Weird Parts....342

The Evolving any Type....342

Excess Property Warnings....344

No Excess Property Checks on Variables....345

No Excess Property Checks When Comparing Functions....346

Open vs. Closed Object Types....348

Fresh and Stale Objects....349

Object Keys Are Loosely Typed....350

The Empty Object Type....352

The Type and Value Worlds....354

Classes Can Cross Between Worlds....356

Enums Can Cross Between Worlds....357

The this Keyword Can Cross Between Worlds....358

Naming Types and Values the Same....359

Using this in Functions....361

Arrow Functions Don’t Support this....364

Function Assignability....364

Unions of Functions Intersect Parameters....368

Exercise 12-1: Accepting Anything Except null and undefined....371

Exercise 12-2: Detecting Excess Properties in an Object....372

Exercise 12-3: Detecting Excess Properties in a Function....375

Exercise 12-4: Iterating over Objects....377

Exercise 12-5: Function Parameter Comparisons....380

Exercise 12-6: Unions of Functions with Object Params....383

Exercise 12-7: Unions of Functions with Incompatible Parameters....385

Summary....387

Part V: Understanding the Environment....388

13. Modules, Scripts, and Declaration Files....389

Understanding Modules and Scripts....389

Modules Have Local Scope....389

Scripts Have Global Scope....390

TypeScript Guesses Which to Use....391

Forcing Modules with moduleDetection....393

Declaration Files....393

Declaration Files Describe JavaScript....393

Declaration Files Can Add to the Global Scope....396

Declaration Files Can’t Contain Implementations....396

The declare Keyword....397

Typing Global Variables....397

Scoping Global Variables to One File....398

More Ways to declare....399

Module Augmentation vs. Module Overriding....401

Declaration Files You Don’t Control....403

TypeScript’s Types....403

DOM Types....404

Types That Ship with Libraries....406

DefinitelyTyped....407

The skipLibCheck Config Option....408

Authoring Declaration Files....409

Should You Store Your Types in Declaration Files?....411

Is Using Global Types a Good Idea?....411

Exercise 13-1: Typing a JavaScript Module....412

Exercise 13-2: Ambient Context....413

Exercise 13-3: Modifying window....414

Exercise 13-4: Modifying process.env....416

Summary....418

14. Configuring Typescript....419

Recommended Configuration....419

Additional Configuration Options....421

The Complete Base Configuration....421

Base Options....422

target....422

esModuleInterop....423

isolatedModules....424

Strictness Options....425

noUncheckedIndexedAccess....426

Other Strictness Options....428

The Two Choices for module....429

NodeNext....429

Preserve....430

noEmit....431

Source Maps....432

Transpiling Code for Library Use....432

outDir....432

Creating Declaration Files....433

Declaration Maps....435

jsx....436

A Note on Node’s TypeScript Support....436

Managing Multiple TypeScript Configurations....439

How TypeScript Finds tsconfig.json....439

Extending Configurations....441

--project....443

Project References....444

Summary....446

Part VI: Advanced Application Development....447

15. Designing Your Types....448

Generic Types....448

Multiple Type Parameters....452

All Type Arguments Must Be Provided....454

Default Type Parameters....454

Type Parameter Constraints....455

Template Literal Types in TypeScript....458

Combining Template Literal Types with Union Types....458

Transforming String Types....459

Conditional Types....460

Mapped Types....461

Key Remapping with as....464

Using Mapped Types with Union Types....465

Exercise 15-1: Creating a DataShape Type Helper....466

Exercise 15-2: Typing PromiseFunc....467

Exercise 15-3: Working with the Result Type....469

Exercise 15-4: Constraining the Result Type....471

Exercise 15-5: A Stricter Omit Type....473

Exercise 15-6: Route Matching....476

Exercise 15-7: Sandwich Permutations....477

Exercise 15-8: Attribute Getters....479

Exercise 15-9: Renaming Keys in a Mapped Type....481

Summary....483

16. Building Powerful Shared Utilities....485

Generic Functions....486

Generic Function Type Alias vs. Generic Type....487

Missing or Conflicting Type Arguments....487

There Is No Such Thing as a “Generic”....489

The Problem Generic Functions Solve....490

Debugging the Inferred Type of Generic Functions....491

Type Parameter Defaults....492

Constraining Type Parameters....493

Type Predicates....494

Assertion Functions....497

Function Overloads....499

The Implementation Signature....500

Function Overloads vs. Unions....502

Exercise 16-1: Making a Function Generic....503

Exercise 16-2: Default Type Arguments....505

Exercise 16-3: Inference in Generic Functions....507

Exercise 16-4: Type Parameter Constraints....510

Exercise 16-5: Combining Generic Types and Functions....512

Exercise 16-6: Multiple Type Arguments in a Generic Function....516

Exercise 16-7: Assertion Functions....519

Summary....522

Index....523

A no-nonsense guide to all the essentials you’ll need to become a TypeScript wizard and build a TypeScript application from scratch.

TypeScript makes JavaScript safer and your editor smarter. Matt Pocock’s Total TypeScript courses have trained thousands of developers by putting the editor first: You learn types by watching what TypeScript tells you, not by memorizing rules. This book brings that method to print.

You’ll start by setting up a proper TypeScript environment, then immediately begin writing and annotating code. Each chapter builds on the last—primitive types to unions, objects to classes, basic generics to type transformations—with exercises woven throughout as checkpoints, not afterthoughts.

Later chapters tackle what takes longer to learn: deriving types from other types, writing type predicates and assertion functions, configuring the compiler for real projects, and building type architectures that don’t collapse under their own weight.

You’ll learn to:

  • Read TypeScript’s error messages and use your editor as a teaching tool
  • Write precise types for objects, functions, and classes
  • Use unions, narrowing, and generics to make types flexible without losing safety
  • Derive and transform types so you don’t repeat yourself
  • Configure tsconfig.json for React, Node, or library development

This is a workshop in print. The one Matt Pocock has been refining for years.


Похожее:

Список отзывов:

Нет отзывов к книге.