Sub topic 2
`any`: Opting Out of Type Checking
Assume you know TypeScript type annotations, interfaces, and union types. You should also be able to run tsc or use an editor that reports TypeScript errors.
The any type tells TypeScript to stop checking a value. A variable of type any can hold any value, and you can perform almost any operation on it. TypeScript allows the code to compile, even when the operation will fail at runtime.
let value: any = "hello";
value.toUpperCase(); // allowed
value.toFixed(); // allowed by TypeScript, but fails at runtime
value.missing(); // also allowed
value = 42; // allowedThe second and third calls are unsafe because a string does not have toFixed or missing methods. The compiler cannot protect you after any enters an expression.
How `any` spreads
An any value can flow into other variables, function arguments, object properties, and return values. This spread is sometimes called any contamination. One unchecked value can remove useful checking from a larger part of the program.
function formatUser(user: { name: string }): string {
return user.name.toUpperCase();
}
const externalValue: any = {
name: 123
};
console.log(formatUser(externalValue)); // compiles
// Runtime result: TypeError, because 123 has no toUpperCase methodexternalValue is accepted as an argument even though its name property has the wrong type. Assignability checks are relaxed when any is involved.
The following table shows why any is dangerous:
| Expression | TypeScript result | Possible runtime result |
|---|---|---|
| `value.missing()` | Allowed | A `TypeError` |
| `value * 2` | Allowed | `NaN` or an unexpected number |
| `value.name` | Allowed | `undefined` |
| `const s: string = value` | Allowed | A non-string value in `s` |
`any` compared with `unknown`
any and unknown can both receive values of any type. Their important difference is what happens next. any allows use without a check. unknown requires narrowing before most operations.
let a: any = "hello";
a.toFixed(); // Compiles, but throws a TypeError at runtime
let u: unknown = "hello";
// u.toUpperCase(); // Error: 'u' is of type 'unknown'
if (typeof u === "string") {
console.log(u.toUpperCase()); // Safe: u is narrowed to string
}Use unknown at a boundary where data has not been validated yet, such as a JSON response or a value supplied by a library. The next chapter explains narrowing in detail.
When `any` is justified
Avoid any in new application code when unknown, a specific type, or a generic type can express the situation. Still, any can be practical in limited cases:
- Migrating a large JavaScript codebase in small steps.
- Interacting with an old library whose declarations are inaccurate.
- Typing a deliberately dynamic operation that has its own runtime validation.
- Temporarily isolating an error while you create a better type.
Keep the value inside a small adapter. Convert it to a checked type before returning it to the rest of the application.
Preventing accidental `any`
Enable noImplicitAny so TypeScript reports parameters and variables that would otherwise receive any implicitly.
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true
}
}The strict option enables a group of safer checks. Lint rules such as @typescript-eslint/no-explicit-any can also report written any annotations. During migration, allow exceptions only where they include a reason and have a clear boundary.
Exercise
Why does formatUser(externalValue) compile when externalValue has name: 123, and what is the safer replacement for an unvalidated external value?
Show answer
The value is typed as any, which disables normal assignability checks. Use unknown at the boundary, validate its shape, and pass the validated result as the expected user type.