Why You Should Avoid Using any (and What to Do Instead)
any
is a special TypeScript type that tells the compiler:
"Trust me, I know what I'm doing."
When you use any
, TypeScript turns off type checking for that variable — which defeats the purpose of using TypeScript in the first place.
let data: any = "hello";
data.toFixed(); // No error, but will crash at runtime
Why Overusing any is a Problem
The biggest benefit of TypeScript is catching bugs before they happen. any
disables that:
function handleUser(user: any) {
// You might assume this is safe, but it's not
console.log(user.name.toUpperCase());
// It will crash if `user.name` is undefined or not a string
}
Plus, you miss out on one of the best developer experience features of TypeScript:
Helpful autocompletion and suggestions from your IDE!
const user: any = getUser();
user. // <- No suggestions 😭. You're flying blind.
What to Use Instead
Use unknown over any
If you truly don’t know the type yet, use unknown
. It forces you to do checks before using the value:
function handle(data: unknown) {
if (typeof data === "string") {
console.log(data.toUpperCase());
}
}
Use Partial, Pick, etc. for Flexibility
TypeScript utility types let you write more flexible types without giving up safety:
type UserUpdate = Partial<User>;
More can be found in the Utility Types section.
Ending notes
Rule of Thumb:
If you’re using
any
, ask yourself: “What am I losing in type safety by doing this?”
Last updated