Course contentsShow
← TypeScript
Lesson 942 of 1,79621. The unknown TypeFree lesson

When NOT to Use unknown

Avoid unknown for internal data already validated; use specific types to maintain type safety through your codebase.

When NOT to Use unknown

You'll learn: When unknown is the wrong choice and specific types are better for maintaining type safety through your codebase.

The Core Idea

While unknown is perfect for external, unvalidated data (like API responses or user input), it's a terrible choice for internal data that you've already validated or that comes from trusted sources within your application. Using unknown for data you already know about throws away type safety and forces unnecessary narrowing everywhere.

Think of it like security checkpoints: you check someone's ID at the building entrance, but you don't ask every employee to show their badge at every single door inside. Once data passes initial validation and enters your type-safe domain, use specific types.

When unknown Is Wrong

Already-validated data:

// ❌ Bad: Using unknown after validation
function processUser(data: unknown) {
  // You already validated this!
  if (typeof data === 'object' && data !== null && 'name' in data) {
    // Still working with unknown inside...
  }
}

// ✅ Good: Accept the validated type directly
function processUser(user: { name: string; age: number }) {
  // Type-safe from the start
  console.log(user.name.toUpperCase());
}

Internal function returns:

// ❌ Bad: Your own functions shouldn't return unknown
function getUserFromDatabase(id: string): unknown {
  // You control this! Return the real type
  return { id, name: "Alice", age: 30 };
}

// ✅ Good: Return specific types from internal functions
function getUserFromDatabase(id: string): User {
  return { id, name: "Alice", age: 30 };
}

Type-safe data transformations:

// ❌ Bad: Erasing known types with unknown
function doubleNumbers(nums: number[]): unknown[] {
  return nums.map(n => n * 2); // Why lose the type?
}

// ✅ Good: Preserve type information
function doubleNumbers(nums: number[]): number[] {
  return nums.map(n => n * 2);
}

The Real Rule

Use unknown at the boundary where untrusted data enters your system (API responses, JSON parsing, user uploads). Once validated, immediately convert to specific types and use those throughout your codebase. unknown is for the perimeter, not the interior.

Key Takeaway: Avoid unknown for internal data already validated—use specific types to maintain type safety through your codebase. unknown marks trust boundaries, not everyday operations.