Use `any` when a value must retain JavaScript’s flexibility rather than be limited to one statically checked type. A parameter, function result, or variable annotated `any` can accept values of any type. The trade-off is that TypeScript no longer checks whether operations on that value make sense; you take responsibility for the result. section 7.2.3
A calculation that compiles but fails at runtime
In `src/index.ts`, `function calculateTax(amount: any): any { return `$${(amount * 1.2).toFixed(2)}`; }` returns a formatted string. `let taxAmount = calculateTax(100); let halfShare = taxAmount / 2;` compiles, but `halfShare` is `NaN`: the currency symbol prevents JavaScript from converting the string to a number. Assigning the result to `let myNumber: number` also compiles if the result is held in an `any` variable; calling `myNumber.toFixed(2)` then throws a `TypeError` because the runtime value is still a string. section 7.2.3
Listing 7.18 Assigning the any type in the index.ts file in the src folder
function calculateTax(amount: any): any {
return `$${(amount * 1.2).toFixed(2)}`;
}
let price = 100;
let taxAmount = calculateTax(price);
let halfShare = taxAmount / 2;
console.log(`Price: ${price}`);
console.log(`Full amount in tax: ${taxAmount}`);
console.log(`Half share: ${halfShare}`);
let newResult: any = calculateTax(200);
let myNumber: number = newResult;
console.log(`Number value: ${myNumber.toFixed(2)}`);
Follow the complete `src/index.ts` listing from the `any` return value through the unchecked number assignment to the failing method call. section 7.2.3
`any` can also appear without an explicit annotation:
- If the compiler cannot infer a parameter type, it may use `any`. Removing the annotation from `calculateTax(amount)` permits a string argument that produces `$NaN`; setting `noImplicitAny` to `true` in `tsconfig.json` instead reports the untyped parameter. section 7.2.3
- An empty `prices` array can be inferred as `any[]`, allowing numbers and a string to mix unnoticed. Give the array an explicit type to close that gap. In the shown configuration, enabling `strictNullChecks` instead makes the empty array infer `never`, so adding values fails compilation. section 9.2.3
- Imported JavaScript without static type information can leave parameters and results treated as `any`. A formatter that expects a number then accepts a string at compile time and fails when it calls `toFixed`. section 15.3
Choose a narrower type when the allowed values are known. A `string | number` union, for example, permits both values while restricting operations to those available on both types. `unknown` offers deliberate access to dynamic values with restrictions on their use. Even an `as any as boolean` assertion can silence a warning without changing the runtime value. section 7.3 section 7.4.1 section 7.2.3

