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 ...

Get Effective TypeScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.