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 ...
Get Effective TypeScript 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.