Sub topic 2
any: opting out of type checking
This chapter assumes you know basic TypeScript syntax (annotations, interfaces, union types) and can run tsc or use an editor with TypeScript support. It covers what any does, where it comes from, and why one any rarely stays in one place. The next chapters cover unknown, the safe alternative.
What any means
any is a type that turns off checking for a value. The compiler stops asking what the value is and accepts every operation on it: property reads, calls, arithmetic, indexing, and assignment.
let value: any = "hello";
value.toFixed(); // compiles, but throws a TypeError at runtime
value(); // compiles, but throws a TypeError at runtime
value.a.b.c = 1; // compiles, but throws a TypeError at runtime
value = 42; // reassigning to a different type is fine
console.log(value.toFixed(2)); // "42.00"None of the three failing lines produce a compiler error. The checks that would have caught them are gone. any does not mean "some type the compiler can't determine." It means "do not check this value at all."
Assignability in both directions
Most types accept values from only one side. A string variable accepts strings but not numbers. any is different because it works in both directions:
- Any value can be assigned to a variable of type
any. - A value of type
anycan be assigned to a variable of any other type.
let anything: any = { id: 1 };
const s: string = anything; // no error
const n: number = anything; // no error
const list: string[] = anything; // no error
anything = "text";
anything = [1, 2, 3];
anything = undefined;After const n: number = anything, the compiler believes n is a number. It holds an object. TypeScript trusts the declared type of n from that point on, so the lie travels with it.
The one exception is never. A value of type any cannot be assigned to never.
declare const anything: any;
const impossible: never = anything;
// error: Type 'any' is not assignable to type 'never'.This is why any is described as sitting at the top of the type system, but behaving unlike a normal top type. A true top type accepts every value but gives nothing back unless you check it first. any accepts everything and also hands back anything you ask for.
Operations on any produce more any
Reading a property from an any value gives any. Calling an any value gives any. Indexing it gives any. So one any at the start of a chain makes the whole chain unchecked.
function parse(json: string) {
return JSON.parse(json); // JSON.parse is declared to return any
}
const result = parse('{"user":{"name":"Ada"}}');
const user = result.user; // any
const name = user.name; // any
const upper = name.toUpperCase(); // any
const typo = result.usr.name; // any, compiles, throws at runtimeparse has no return type annotation, so TypeScript infers any from JSON.parse. Every caller then receives an unchecked value, and so does every variable assigned from it.
Spreading also happens through other types. Putting any inside a larger type often keeps the unchecked part:
type Mixed = string | any; // collapses to any
type Both = { id: number } & any; // collapses to any
const items: any[] = [1, "two", { three: 3 }];
const first = items[0]; // any
const lookup: Record<string, any> = {};
lookup.anything.goes.here; // anyA union that includes any becomes any, so the string in Mixed adds nothing. This is easy to miss when you read a type alias.
What you lose
The cost is not only runtime errors. When a value is any, you also lose:
- Autocomplete and signature help, because the editor has no members to suggest.
- Rename refactoring. Renaming a property in an interface does not update accesses on
anyvalues. - Return type inference. A function that returns an
anyexpression has return typeany, so its callers lose checking too. - Error messages at the right place. A wrong shape fails far from where the bad data entered the program.
| Operation | On a typed value | On an `any` value |
|---|---|---|
| Misspelled property | Compile error | Compiles, `undefined` at runtime |
| Call with wrong argument count | Compile error | Compiles |
| Assign to `string` variable | Only if it is a string | Always allowed |
| Autocomplete | Lists members | Lists nothing useful |
| Result of the operation | A known type | `any` |
Explicit and implicit any
There are two ways a value becomes any.
Explicit any is written by someone: let x: any, function f(a: any), as any, or Array<any>. It is a visible decision, and a reviewer or a lint rule can find it.
Implicit any happens when TypeScript cannot infer a type and has no annotation to use, so it falls back to any. With default settings and no strict mode, this fallback is silent.
function double(n) { // n is implicitly any
return n * 2; // return type is number, but n is unchecked
}
double("abc"); // compiles, returns NaNThe compiler option noImplicitAny turns this fallback into an error. Under that option, the same code fails with Parameter 'n' implicitly has an 'any' type. (error 7006). You fix it by writing an annotation: function double(n: number). The option is part of the strict family and is covered in a later chapter. Here the point is that it only catches implicit any.
A common surprise: JSON.parse returning any is not an implicit any. The standard library declares that return type explicitly, so noImplicitAny stays quiet. The same applies to Response.json() in the fetch API, which returns Promise<any>. Enabling strict mode does not remove any that comes from declarations.
One case looks like implicit any but is not. A variable declared without a type or initializer, such as let x;, gets an evolving type under noImplicitAny. TypeScript tracks the assigned values through the control flow and narrows accordingly. Without that option, the variable is plain any.
When any is the right tool
any is a legitimate tool in a small number of places.
Function types that must accept any parameters. Function parameters are checked contravariantly under strictFunctionTypes, so a function that takes string is not assignable to a function type that takes unknown. A generic helper that wraps arbitrary functions needs any in its parameter list:
type Handler = (...args: unknown[]) => void;
type LooseHandler = (...args: any[]) => void;
const greet = (name: string) => console.log(`Hello, ${name}`);
// const h1: Handler = greet; // error: parameter types are not compatible
const h2: LooseHandler = greet; // OK
h2("Ada"); // prints "Hello, Ada"Constraints such as F extends (...args: any[]) => any are common in libraries for this reason. The any here sits in a constraint, not in a value your code reads.
Gradual migration from JavaScript. When you convert a large JavaScript codebase, annotating a module as any lets the build pass while you work file by file. This is a temporary state that you track and remove.
Test doubles and deliberate escape hatches. A test that builds a partial mock may cast it with as any to skip fields it does not use. Keep these casts in test files, not in production code.
In each case, any should be small, visible, and have a stated reason. If you cannot say why the value must be unchecked, the type you want is probably unknown.
Finding any in your code
You will meet any mostly through values you did not annotate yourself. Common sources:
JSON.parse()andResponse.json()results.- Third-party packages without type declarations. An import from a module with no types gives
anywhennoImplicitAnyis off, and an error when it is on. - Callbacks passed to loosely typed APIs.
catchclause variables in older configurations, where the variable defaults toany.- Existing
as anycasts that someone added to silence an error.
Hovering over a variable in the editor shows any when this has happened. If a hover shows any on something you expected to be typed, trace it back to the source and fix it there. Adding an annotation at the end of the chain hides the problem for that one variable but leaves any in the rest.
Exercise
In the code below, what is the type of total, and does the compiler report an error? Explain why, and say where you would add a single annotation to restore checking.
const data = JSON.parse('{"price": "10", "qty": 2}');
const total = data.price * data.qty;
console.log(total.toFixed(2));
Show answer
data is any because JSON.parse is declared to return any. data.price and data.qty are any, and multiplying two any values gives number, so total is number and the code compiles without an error. At runtime "10" * 2 evaluates to 20, so it happens to work here, but the compiler never checked that price is a number, and a missing field would give NaN. The best fix is at the source: annotate data with the expected shape or treat the parsed value as unknown and validate it. The unknown approach is the topic of the next chapter. Annotating total only would leave data unchecked.
Exercise
Why does const x: never = anything fail when anything is of type any, even though any can be assigned to every other type? What does that tell you about how any relates to never?
Show answer
never is the type with no values, so TypeScript refuses to assign any to it, since any could hold a value. any is assignable to every type except never. This is a deliberate exception that keeps never meaningful as "this can't happen." It also shows that any is a special rule in the compiler and not simply the union of all types.