Sitemap

Hello unknown

Mar 2, 2025

Seeing a lot of any in your TypeScript code?

Get Itai Klapholtz’s stories in your inbox

Join Medium for free to get updates from this writer.

One way to handle this is by using unknown- a safer alternative.
Like any, it allows you to store a value without knowing its type. However, unlike any, it forces you to check the variable's type before using it.

You can assign any value to an unknown variable, just like with any, but you cannot assign an unknown value to anything else (except any or another unknown) without a type assertion.

Sometimes, despite making the code a bit more cumbersome, unknown is the right choice. It depends on the specific case.
From my experience, it can improve code readability and, more importantly, reduce the risk of runtime errors in production.

--

--