Menu

1 / 2

Stop using any. Use unknown instead

DEV Community·Rocky Chowdhury·6 months ago
#3oLO9aCp
#using#typescript#cleancode#type#value
Reading 0:00
15s threshold

TypeScript's main job is to catch type bugs at compile time, before your code ever runs. But there are two types designed for the "I don't know the type yet" situation — any and unknown — and they behave very differently. One opts you out of the type system entirely. The other keeps you safe.

The problem with any

When you annotate something as any , you're telling TypeScript: "Trust me, I know what I'm doing — stop checking." TypeScript steps aside and lets you do whatever you want with that value, with zero verification.

function parseInput ( input : any ) { return input . toUpperCase (); }

parseInput ( 21 ); // No compile error — but crashes at runtime // TypeError: input.toUpperCase is not a function

Enter fullscreen mode

Exit fullscreen mode

TypeScript doesn't check that 21 is a number, not a string. It happily compiles the code.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.