What is the difference between unknown and any in TypeScript?

any disables type checking entirely; unknown is the type-safe alternative you must narrow the type before using it.

TypeScript

Overview

`any` is an escape hatch that turns off TypeScript's type system for that value you can do anything with it and TypeScript won't warn you. `unknown` is the type-safe equivalent: you can receive any value, but you must check the type before operating on it.

Key Points

  • •`any` lets you call any method, access any property, and assign to any type all without errors.
  • •`unknown` requires a type check (`typeof`, `instanceof`, or a type guard) before use.
  • •Prefer `unknown` for values whose type you genuinely don't know (API responses, error objects).
  • •In catch blocks, the error is `unknown` by default in strict mode always narrow it.
  • •Using `any` propagates: if a function returns `any`, callers lose type safety too.

Examples

any vs unknown in practice

typescript
let a: any     = "hello";
let u: unknown = "hello";

a.toUpperCase(); // OK no type check needed (unsafe)
u.toUpperCase(); // Error: Object is of type 'unknown'

// To use unknown, narrow first
if (typeof u === 'string') {
  u.toUpperCase(); // OK TypeScript now knows it's a string
}

Handling errors safely with unknown

typescript
try {
  await fetchData();
} catch (error: unknown) {
  if (error instanceof Error) {
    console.error(error.message); // safe
  } else {
    console.error('Unknown error', error);
  }
}

Type guard to narrow unknown

typescript
function isApiError(value: unknown): value is { code: number; message: string } {
  return (
    typeof value === 'object' &&
    value !== null &&
    'code' in value &&
    'message' in value
  );
}

if (isApiError(responseBody)) {
  console.error(responseBody.code, responseBody.message);
}

Pro Tip

Treat `any` like a TypeScript `// @ts-ignore` sometimes necessary, always a red flag. When you truly don't know the type, use `unknown` and write a type guard. When you need to opt out for a specific assignment, use a type assertion (`as Type`) at the narrowest possible scope.