#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 27 of 48easy

What is the difference between unknown and any?

Type-safe alternative to any.

What You'll Learn

  • any type
  • unknown type
  • When to use each

any Type

Disables type checking entirely.

code.tsTypeScript
let value: any = "hello";

// No errors, but dangerous!
value.foo.bar.baz;
value();
value.toUpperCase();
value = 42;

unknown Type

Type-safe counterpart to any. Requires type checking before use.

code.tsTypeScript
let value: unknown = "hello";

// Errors! Must check type first
value.toUpperCase(); // Error
value.foo;           // Error

// After type checking, OK
if (typeof value === "string") {
  value.toUpperCase(); // OK
}

Comparison

Featureanyunknown
Assignable toEverythingOnly unknown/any
OperationsAll allowedMust narrow first
Type safetyNonePreserved

When to Use

code.tsTypeScript
// Use unknown for values from external sources
async function fetchData(): Promise<unknown> {
  const response = await fetch("/api");
  return response.json();
}

// Use any only when migrating JS or with problematic libs
declare const legacyLib: any;