DEV Community

Cover image for any, unknown, and never in TypeScript: What’s the Difference?
Mía Salazar
Mía Salazar

Posted on

any, unknown, and never in TypeScript: What’s the Difference?

TypeScript gives developers several ways to describe values that do not fit neatly into a specific type. Three of the most important, and most frequently misunderstood, are any, unknown, and never.

any: opting out of type checking

The any type effectively tells TypeScript: “I know what I’m doing; don’t check this value. Once a value is typed as any, you can perform almost any operation on it without TypeScript complaining.

The flexibility of any can be useful when migrating an existing JavaScript project to TypeScript, working with poorly typed third-party libraries, or dealing with genuinely dynamic code.

The problem is that any removes one of TypeScript’s main benefits: static safety. TypeScript will happily accept code that can fail at runtime. For that reason, any should generally be used deliberately rather than as a convenient way to silence type errors.

unknown: a value whose type you must check

unknown also represents a value whose exact type is not known. The crucial difference is that TypeScript does not allow you to use an unknown value as though you already knew its type. Before using the value, you have to narrow its type.

let value: unknown = "hello";

value.toUpperCase(); // Error

if (typeof value === "string") {
  console.log(value.toUpperCase());
}
Enter fullscreen mode Exit fullscreen mode

This makes unknown particularly useful for data coming from outside your application, such as API responses, parsed JSON, user input, or values received from JavaScript code.

The compiler forces us to establish what the value actually is before performing operations on it.This is the main distinction between any and unknown: any lets you do anything; unknown makes you prove what you can do.

never: a value that cannot exist

never is fundamentally different from both any and unknown. While unknown represents any possible value, never represents no possible value at all. A function that always throws an exception is a classic example.

Conclusion

Although any, unknown, and never can all appear in code involving uncertain or unusual values, they have almost opposite meanings.

any removes type safety. It gives you maximum flexibility at the cost of compiler guarantees.

unknown preserves type safety. It allows you to represent an arbitrary value while requiring you to establish its type before using it.

never represents the absence of a possible value. It is particularly powerful for functions that cannot return and for making TypeScript verify that all cases in a union have been handled.

A good TypeScript codebase will therefore tend to use unknown at uncertain boundaries, reserve any for situations where opting out is genuinely justified, and use never to express impossible states and exhaustive logic.

Top comments (0)