Skip to Content
Effective TypeScript
book

Effective TypeScript

by Dan Vanderkam
October 2019
Intermediate to advanced
261 pages
6h 14m
English
O'Reilly Media, Inc.
Book available
Content preview from Effective TypeScript

Chapter 5. Working with any

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 can add types to parts of your program but not others.

This is essential for migrating existing JavaScript codebases to TypeScript bit by bit (Chapter 8). 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.

Item 38: Use the Narrowest Possible Scope for any Types

Consider this code:

function processBar(b: Bar) { /* ... */ }

function f() {
  const x = expressionReturningFoo();
  processBar(x);
  //         ~ Argument of type 'Foo' is not assignable to
  //           parameter of type 'Bar'
}

If you somehow know from context that x is assignable to Bar in addition to Foo, you can force TypeScript to accept this code in two ways:

function f1() {
  const x: any = expressionReturningFoo();  // Don't do this
  processBar(x);
}

function f2() {
  const x = expressionReturningFoo();
  processBar(x as any);  // Prefer this
}

Of these, the second form is vastly preferable. Why? Because the any type is scoped to a single expression in a function argument. It has no effect outside this argument or this line. If code after the processBar call references ...

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

Effective TypeScript, 2nd Edition

Effective TypeScript, 2nd Edition

Dan Vanderkam
Understanding TypeScript

Understanding TypeScript

Maximilian Schwarzmüller
Learning TypeScript

Learning TypeScript

Josh Goldberg

Publisher Resources

ISBN: 9781492053736Errata Page