What if blindly trusting your data could break your whole app without warning?
Unknown type vs any type in Typescript - When to Use Which
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.
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.
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.
let data: any = fetchData(); console.log(data.name.toUpperCase());
let data: unknown = fetchData(); if (typeof data === 'object' && data !== null && 'name' in data) { console.log((data as { name: string }).name.toUpperCase()); }
This concept enables you to write safer programs that catch mistakes early by making you verify unknown data before using it.
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.
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.