TypeScript any vs unknown: Why any Turns Off the Type Checker (video)

any switches off type checking; unknown keeps it on and makes you narrow first. Learn the difference with examples, safer alternatives to any, the compiler and lint settings that help, and how to find every any in a repo.

Read the full article

Transcript

TypeScript any vs unknown: Why any Turns Off the Type Checker. Here's the short version.

any is TypeScript's escape hatch: a value typed any can be used as anything, and the compiler stops checking it. unknown also accepts any value, but you have to prove what it is before you use it.

The difference. any: you can assign it anywhere, call it, and read any property. unknown: you can assign anything to it.

Here's an example: any compiles and crashes at runtime; unknown makes you check first.

After: unknown plus validation. For larger payloads, a schema library such as Zod or Valibot writes the type guard for you and gives clear error messages.

Safer alternatives to any. unknown for values you have not checked yet (API responses, JSON.parse, catch variables). Generics when a function works with many types but must keep them consistent. Union types when a value can be one of a few known shapes. Record<string, T> for dictionaries instead of any objects.

Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.

More videos

All videos