Skip to Content
Effective TypeScript, 2nd Edition
book

Effective TypeScript, 2nd Edition

by Dan Vanderkam
April 2024
Beginner to intermediate
404 pages
10h 6m
English
O'Reilly Media, Inc.
Content preview from Effective TypeScript, 2nd Edition

Chapter 5. Unsoundness and the any Type

Type systems were traditionally binary affairs: either a language had a fully static type system or a fully dynamic one. TypeScript blurs the line, because its type system is optional and gradual. You’re free to add types to parts of your program but not others.

This is essential for migrating existing JavaScript codebases to TypeScript bit by bit (Chapter 10). Key to this is the any type, which effectively disables type checking for parts of your code. It is both powerful and prone to abuse. Learning to use any wisely is essential for writing effective TypeScript. This chapter walks you through how to limit the downsides of any while still retaining its benefits.

The any type is just the most extreme example of the more general problem of unsoundness: when a symbol’s static type does not match its runtime type. Even if you eliminate all the anys from your code, you may still fall into soundness traps. Item 48 presents a few of these and shows you how to avoid them.

Item 43: Use the Narrowest Possible Scope for any Types

Consider this code:

declare function getPizza(): Pizza;
function eatSalad(salad: Salad) { /* ... */ }

function eatDinner() {
  const pizza = getPizza();
  eatSalad(pizza);
  //       ~~~~~
  // Argument of type 'Pizza' is not assignable to parameter of type 'Salad'
  pizza.slice();
}

If you somehow know that this call to eatSalad is OK, the best way forward is to adjust your types so that TypeScript understands that, too. (An arugula pizza ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming TypeScript

Programming TypeScript

Boris Cherny

Publisher Resources

ISBN: 9781098155056Errata PageSupplemental Content