The any
type is an escape hatch—it allows you to effectively turn off Typescript’s type checking. Sometimes, there just isn’t a good way to tell Typescript what you are doing, so you use any
to work around that.
And types are not necessarily any
when you leave off a type annotation—in many cases, Typescript will infer a type, and then enforce that. let x = 2;
will infer x
as having type number
—and using x = "cat";
later will create an error. In such cases, you must use any
if that’s what you want.
There are other cases where you have to use any
explicitly, and could not just “leave it out,” for example, with generic types:
type Pair<A, B> = [A, B];
declare function needsSomethingPairedWithString(value: Pair<any, string>): void;
For this needsSomethingPairedWithString
function, we don’t care what the first element of the pair is—maybe we’ll test its type, maybe we won’t even use it, whatever, but the point is we don’t care. But we want to specify that the second element of the Pair
is string
. So we need to write Pair<any, string>
to indicate that.
In many cases it is preferable to use unknown
to any
for these kinds of purposes—unknown
’s meaning is closer to “don’t know and don’t care” than any
’s is. However, particularly when dealing with constraints, any
can be the correct type.
Finally, note the existence of the --noImplicitAny
compiler flag: this will cause cases where any
is inferred for a type to become errors. That forces you to either fix things so they are inferred correctly, annotate the correct type, or at the very least, explicitly annotate the any
type. This is highly recommended for projects that start from the beginning using Typescript—implicit any
should be reserved for projects gradually converting Javascript to Typescript, as it is a potential source of many bugs. Using --noImplicitAny
forces you to be explicit about any
, which means it will be immediately obvious to any developers reading it later that any
is being used. This is important because any
means that things are not going to be as safe as you’d like.