TypeScript: any vs unknown vs never - What Is the Difference?

What is the difference between any, unknown and never?
any means "I give up, do not check this value". unknown means "I do not know what this is yet, so check it before you use it". never means "this value can never exist".
In type theory language, any and unknown can hold any value, and never can hold none. They look similar because of their names, but they solve very different problems. In this post I will explain each of them with small examples and show where they help in real code.
any: turning off the type checker
A value of type any can be anything, and TypeScript lets you do anything with it. You can call it, read properties from it, or assign it to every other type.
let value: any = 'Neo';
value = 42;
value.toUpperCase();
// No error at compile time
// Output at runtime: TypeError: value.toUpperCase is not a function
const level: number = value;
// No error, even if value is not a number
The code compiles, and then it crashes in the browser. This is the main problem with any: it removes the safety that you wanted from TypeScript.
It also spreads. Everything you take from an any value is any too, so one weak place can switch off type checking in a big part of the code.
function getPlayer(): any {
return { nickname: 'Neo', level: 1 };
}
const player = getPlayer();
const name = player.nickname; // name is any
const upper = name.toUpperCase(); // upper is any
There are only a few good reasons to use any: moving an old JavaScript project to TypeScript step by step, or working with a library that has no types at all. Even then, it should be temporary.
unknown: the safe version of any
Like any, a value of type unknown can hold anything. The difference is that TypeScript does not let you use it until you prove what it is.
let value: unknown = 'Neo';
value.toUpperCase();
// Error: 'value' is of type 'unknown'
const level: number = value;
// Error: Type 'unknown' is not assignable to type 'number'
To use it, you need to narrow the type first. This is done with checks like typeof, instanceof or a custom type guard:
function shout(value: unknown): string {
if (typeof value === 'string') {
return value.toUpperCase(); // here value is string
}
return 'Not a string';
}
console.log(shout('neo'));
// Output: NEO
console.log(shout(42));
// Output: Not a string
Inside the if, TypeScript knows that value is a string, so everything works. Outside of it, you still have to be careful.
You can assign any value to unknown, but you can assign unknown only to unknown and any. That is why it is safe: the unchecked value cannot slip into the rest of your code.
A simple rule: if you do not know the type, use unknown, not any.
never: a value that cannot exist
never is the type of something that never happens. No value has this type, so you cannot assign anything to a never variable (except another never).
The first place you meet it is a function that never returns, because it always throws an error or runs forever:
function fail(message: string): never {
throw new Error(message);
}
function loop(): never {
while (true) {}
}
Compare it with void. A void function finishes and returns nothing. A never function does not finish at all.
The second place is a type that has been narrowed down until nothing is left:
function check(value: string | number) {
if (typeof value === 'string') {
// value is string
} else if (typeof value === 'number') {
// value is number
} else {
// value is never: all cases were already handled
}
}
TypeScript also uses never when a union has nothing in common, for example string & number, and it disappears from unions: string | never is just string.
This "impossible" type sounds useless, but it is a perfect tool for checking that you handled every case, as you will see in the next section.
Exhaustive switch with never
Imagine a function that calculates the area of different shapes:
type Shape =
{ kind: 'circle'; radius: number }
| { kind: 'square'; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.side ** 2;
default: {
const unreachable: never = shape;
return unreachable;
}
}
}
After the two case branches, TypeScript knows that nothing is left, so shape in the default branch has the type never. The code compiles.
Now a new teammate adds a new shape, but forgets to update area:
type Shape =
{ kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'triangle'; base: number; height: number };
Now shape in the default branch can still be a triangle, so TypeScript reports an error right in the area function:
const unreachable: never = shape;
// Error: Type '{ kind: "triangle"; base: number; height: number; }'
// is not assignable to type 'never'
The compiler tells you about the missing case before the code runs. With a lazy default branch (for example return 0), the function would quietly give a wrong result for a triangle, and nobody would notice.
Because this pattern is useful, many projects keep a small helper:
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
// in the switch:
default:
return assertNever(shape);
This gives you two protections: a compile-time error when a case is missing, and a clear runtime error if bad data still gets through.
Real life: JSON.parse, catch blocks and API data
Where will you meet these types in everyday code?
JSON.parse returns any
const data = JSON.parse('{"nickname": "Neo"}');
// data is any, so TypeScript trusts you completely
data.levl.toFixed(); // typo, but no error until runtime
A safer way is to put the result into unknown and check it:
interface Player {
nickname: string;
level: number;
}
function isPlayer(value: unknown): value is Player {
return (
typeof value === 'object' &&
value !== null &&
'nickname' in value &&
typeof value.nickname === 'string' &&
'level' in value &&
typeof value.level === 'number'
);
}
const data: unknown = JSON.parse('{"nickname": "Neo", "level": 1}');
if (isPlayer(data)) {
console.log(data.nickname); // data is Player here
}
The function isPlayer is a type guard. The part value is Player tells TypeScript: "if this function returns true, treat the value as a Player".
Errors in catch are unknown
In modern TypeScript (with strict mode), the variable in a catch block is unknown, because in JavaScript you can throw anything, not only Error objects.
try {
riskyOperation();
} catch (error) {
// error is unknown
if (error instanceof Error) {
console.log(error.message);
} else {
console.log('Something strange was thrown');
}
}
Function arguments that accept anything
When a function really accepts any value, like a logger, unknown is better than any:
function log(value: unknown): void {
console.log(value); // we only pass it on, never use its properties
}
Quick comparison
any |
unknown |
never |
|
|---|---|---|---|
| Meaning | Any value, no checks | Any value, must be checked | No value at all |
| Can hold any value | Yes | Yes | No |
| Can be assigned to other types | Yes (to everything) | No (only to unknown and any) |
Yes (to everything) |
| Can you use its properties? | Yes, unchecked | Only after narrowing | Not applicable |
| Type safety | None | Full | Full |
| Typical use | Legacy code, no types | External data, catch, JSON.parse |
Functions that throw, exhaustive checks |
Summary
Use any as little as possible, because it switches off the type checker. Use unknown when you do not know the type yet, for example for data from an API, JSON.parse or a catch block, and check it before you use it. Use never for code that cannot finish normally and to make the compiler warn you when a switch or if does not handle every case. If you remember one thing: unknown is the safe any, and never is the "impossible" type that protects you from forgotten cases.
About the author
Front-end developer who pays special attention to the aesthetics and functionality of websites. I love playing with interesting design solutions, creating interfaces that not only work efficiently, but also attract attention with their unique design. I like to derive pleasure from it, like with my old 'Portfolio' website. After hours, I return to classic games or good movies that stimulate the imagination.
Comments
Join the discussionNo comments yet. Be the first to comment.





