0
0
Typescriptprogramming~3 mins

Unknown type vs any type in Typescript - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if blindly trusting your data could break your whole app without warning?

The Scenario

Imagine you are sorting through a big box of mixed items without knowing what each item is. You try to use or fix them without checking, hoping everything works fine.

The Problem

This approach is risky and slow because you might break something or waste time fixing errors caused by wrong assumptions. Without knowing what you have, mistakes happen often.

The Solution

Using the unknown type in TypeScript forces you to check what you have before using it, making your code safer. Unlike any, which lets you do anything and can hide errors, unknown makes you pause and confirm, preventing bugs.

Before vs After
Before
let data: any = fetchData();
console.log(data.name.toUpperCase());
After
let data: unknown = fetchData();
if (typeof data === 'object' && data !== null && 'name' in data) {
  console.log((data as { name: string }).name.toUpperCase());
}
What It Enables

This concept enables you to write safer programs that catch mistakes early by making you verify unknown data before using it.

Real Life Example

When receiving user input or data from the internet, you don't know its shape. Using unknown helps you check the data carefully before trusting it, avoiding crashes or wrong results.

Key Takeaways

any lets you do anything but can hide errors.

unknown forces you to check before use, making code safer.

Using unknown helps catch bugs early and write more reliable programs.