Search⌘ K
AI Features

Understanding any and unknown Types

Explore the differences between TypeScript's any and unknown types to improve code safety. Understand how any disables type checking, while unknown requires validation before use. Learn to apply runtime type guards like typeof, in, and instanceof to narrow unknown, and use type assertions cautiously. This lesson teaches you to safely handle dynamic or uncertain data, avoiding runtime errors and improving your TypeScript code quality.

When TypeScript doesn’t know what something is, it sometimes gives up and infers the type any. This might happen when you’re consuming dynamic data, skipping type annotations, or interacting with poorly typed libraries.

At first, any feels helpful—no more compiler complaints. But here’s the hard truth: any turns off TypeScript’s entire type checking system.

TypeScript 5.8.3
let value: any = "hello";
value(); // no error at compile time — runtime crash
value.trim(); // works
value.toFixed(); // compiles — but crashes at runtime
console.log(`Value: ${value}`);

Explanation:

  • Line 1: The variable is typed as any, so the compiler stops validating what it really is.

  • Line 2: We call the value like a function—TypeScript allows it, but it crashes at runtime.

  • Line 3: This one works, because the value is actually a string.

  • Line 4: This compiles fine but .toFixed() only exists on numbers, not strings. This is another runtime trap.

any is effectively a license to ignore correctness. The code compiles, but any mistake becomes a runtime bug waiting to happen.

Meet unknown: The safer option

unknown solves the same problem as any—but it refuses to abandon safety. It lets us assign any value to a variable, but we can’t use it until we prove what it is.

TypeScript 5.8.3
let input: unknown = "Ada";
input.trim(); // Error!
console.log(`Input is: ${input}`);

Explanation:

  • Line 1: We assign a string to a variable of type unknown.

  • Line 2: Even though it’s a string, we can’t use string methods without first checking or asserting the type.

This makes unknown perfect for handling uncertain or external data. Instead of turning off the compiler, we delay the decision and force ourselves to earn type confidence—TypeScript won’t let us proceed until we prove what the value really is.

any vs. unknown: What’s the difference
any vs. unknown: What’s the difference

Think about when we’re reading from localStorage, calling an API, or accessing a form field, we might receive data with an unknown shape. That’s where the unknown type comes in—it tells TypeScript, “we don’t trust this yet.” We’ll ...