Typescript Foundations / Best Practices and Real World Patterns

When to use any, unknown

🧾 any vs unknown

Feature

any

unknown

Type Safety

❌ No type checking

✅ Safer, requires type checking

Use in operations

✅ Allowed directly

❌ Not allowed without narrowing

Flexibility

✅ Fully flexible

⚠️ Flexible, but requires checking

Default behavior

Can lead to runtime errors

Helps prevent unsafe operations


✅ Use any When:

  • You are gradually migrating JavaScript to TypeScript and don’t know the type yet.

  • You are dealing with 3rd party libraries that lack proper type definitions.

  • You want to bypass TypeScript’s type system temporarily (not recommended in production).

Example:

let value: any = "Hello";
value.toUpperCase(); // No error, but could be risky if value is not a string

✅ Use unknown When:

  • You want a type-safe alternative to any.

  • You're handling dynamic input (e.g., from JSON, APIs, user input).

  • You want to force the developer to do type checking or type narrowing before use.

Example:

let value: unknown = "Hello";
// value.toUpperCase(); ❌ Error

if (typeof value === "string") {
  console.log(value.toUpperCase()); ✅
}

🧠 Summary

Scenario

Use

Not sure about the type (temporary)

any

Input from external or dynamic source

unknown

You want full flexibility (risky)

any

You want flexibility with safety

unknown


🟡 Pro Tip: Avoid any in production code. Prefer unknown with proper checks to keep the benefits of TypeScript’s type safety.

Let me know if you'd like real-world examples (e.g., API handling, form validation, etc.) using unknown.