Logo for tommyjepsen.com
TypeScript: Difference between Unknown and Any?

TypeScript: Difference between Unknown and Any

2023-10-23 • By Tommy Jepsen ✌️

Let's talk about the difference between unknown and any in TypeScript.

There are two places unknown and any differentiate from each other.

Type Safety:

  • unknown: This is TypeScript's way of ensuring type safety when dealing with values of uncertain or changing types. When you have a variable of type unknown, you can't simply perform any operation on it. TypeScript insists that you perform type checks, like using type assertions or type guards, before you can confidently use the value. It's all about keeping your code robust and error-free.
  • any: Now, any takes a different approach. It pretty much throws type safety out the window. It allows you to perform any operation on a value without any type checking. While it can be tempting for some dynamic scenarios, it's generally discouraged because it undermines TypeScript's core purpose, which is type checking.

Type Inference:

  • unknown: When you declare a variable as unknown, TypeScript won't automatically figure out its type based on its initial value. You'll need to explicitly narrow down the type through type checks. It puts the responsibility on us as developers to ensure we're handling unknown types safely.
  • any: On the other hand, when a variable is declared as any, TypeScript just assumes it's, well, anything! This can lead to loss of type information and potential runtime issues.

Here is an example:

let value: unknown;
let anyValue: any;

// These lines will result in type errors
const length = value.length; // Error: Object is of type 'unknown'.
const anyLength = anyValue.length; // No error, even though it might fail at runtime.

// To safely use value, you must perform type checks
if (typeof value === "string") {
  const length = value.length; // OK, type is narrowed to string.
}

In summary, as TypeScript developers, using unknown when you're dealing with values of uncertain types is the way to go. It ensures that type safety is upheld through proper type checking. Try to avoid using any unless you have a really compelling reason to do so, as it goes against TypeScript's mission of providing strong typing and type safety - even though it's the easy way out sometimes ;)