Codington
0 of 6 problems solved0%

any (vs unknown)

6 exercises

any turns off type checking completely. It spreads quickly through your code and hides bugs. Prefer unknown when you don't know a type yet:

// ❌ Dangerous - no checks function process(data: any) { return data.value.toUpperCase(); // Might crash! } // ✅ Safe - forces checks function process(data: unknown) { if (typeof data === "object" && data !== null && "value" in data) { const obj = data as { value: string }; return obj.value.toUpperCase(); } }

unknown forces you to check a value before using it, making your code safer.

Narrowing techniques:

  • typeof for primitives – typeof x === 'string'
  • Array.isArray() for arrays
  • in operator for properties – 'name' in obj
  • Custom type guards – function isUser(x: unknown): x is User

In this category, you'll:

  • Use unknown for inputs you need to validate
  • Narrow safely with runtime checks
  • Parse JSON and validate structures
  • Avoid leaking any into your code
  • Migrate gradually from any to unknown

By the end, you'll understand why unknown is safer than any and how to work with it confidently.

CodingtonCodington

© 2025 Codington. Built with TypeScript, TanStack Start and a lot of console.log().