Careeroza
Why to Avoid any
any Spreads
any is contagious. Anything you read from an any value is also any, so one any can silently remove checking from a whole chain of code.
Example
Compare: with unknown the same mistake is caught at compile time (TS18046) instead of producing NaN in production.
function parseOrder(json: string): unknown {
return JSON.parse(json);
}
const order = parseOrder('{"total": "1200"}');
const withTax = order.total * 1.18;
console.log(withTax);Compiler output (tsc)
Line 6: error TS18046: 'order' is of type 'unknown'.
Better Alternatives to any
| Instead of any, use | When |
|---|---|
unknown | you do not know the type yet and will check it |
a union like string | number | there are a few known possibilities |
| a specific object type or interface | you know the shape of the data |
generics <T> (medium level) | the function works with many types but keeps them connected |
Record<string, unknown> | any plain object with unknown values |
Tip: Turn on the ESLint rule @typescript-eslint/no-explicit-any so nobody adds any by accident.