0
0
Typescriptprogramming~5 mins

Unknown type vs any type in Typescript

Choose your learning style9 modes available
Introduction

We use unknown and any types to handle values when we don't know their exact type. They help us write flexible code but in different ways.

When you get data from an external source like user input or a web API and you don't know its type yet.
When you want to allow any type but still want to check the type before using it.
When you want to skip type checking completely and trust the value is correct.
When you want safer code by forcing checks before using a value.
When you want to quickly disable type checking during development.
Syntax
Typescript
let value: unknown;
let anything: any;

unknown means the value could be anything but you must check its type before using it.

any means the value can be anything and TypeScript will not check it at all.

Examples
With unknown, you must check the type before using it as a number.
Typescript
let data: unknown = 5;
// Need to check type before using
if (typeof data === 'number') {
  console.log(data + 10); // OK
}
With any, TypeScript lets you use the value without checks.
Typescript
let data: any = 5;
console.log(data + 10); // No error, even if data is not a number
unknown forces you to check the type before accessing properties.
Typescript
let value: unknown = 'hello';
// console.log(value.length); // Error: Object is of type 'unknown'.

if (typeof value === 'string') {
  console.log(value.length); // OK
}
any skips all type checks, so you can access properties freely.
Typescript
let value: any = 'hello';
console.log(value.length); // OK, no error
Sample Program

This program shows how to safely use a value of type unknown by checking its type first.

Typescript
function processValue(value: unknown) {
  if (typeof value === 'string') {
    console.log(`String of length ${value.length}`);
  } else if (typeof value === 'number') {
    console.log(`Number plus 10 is ${value + 10}`);
  } else {
    console.log('Unknown type');
  }
}

processValue('hello');
processValue(5);
processValue(true);
OutputSuccess
Important Notes

unknown is safer than any because it forces you to check types before use.

any disables all type checking and can lead to bugs if used carelessly.

Use unknown when you want flexibility but still want type safety.

Summary

unknown means the value could be anything but you must check its type before using it.

any means the value can be anything and TypeScript will not check it at all.

Prefer unknown for safer code and any only when you need to skip checks.