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:
functionprocessBar(b:Bar){/* ... */}functionf() {constx=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:
functionf1() {constx:any=expressionReturningFoo();// Don't do thisprocessBar(x);}functionf2() {constx=expressionReturningFoo();processBar(xasany);// 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 ...