Course contentsShow
← TypeScript
Lesson 888 of 1,79620. The any Escape HatchFree lesson

Type Guards to Narrow unknown

Use typeof, instanceof, and custom type guards to safely narrow unknown values to usable types.

Type Guards to Narrow unknown

What you'll learn: How to safely transform unknown values into specific, usable types using typeof, instanceof, and custom type guards.

The Problem with unknown

Remember that unknown is type-safe but unusable directly—you can't access properties, call methods, or do much of anything without TypeScript complaining. This is by design: unknown forces you to prove what you're dealing with before using it.

The solution? Type guards that narrow unknown to specific types.

Using typeof to Narrow unknown

The typeof operator works perfectly with unknown values:

function processValue(value: unknown) {
  if (typeof value === 'string') {
    // TypeScript now knows value is a string
    console.log(value.toUpperCase());
  } else if (typeof value === 'number') {
    // Here, value is a number
    console.log(value.toFixed(2));
  } else if (typeof value === 'boolean') {
    // And here, a boolean
    console.log(value ? 'yes' : 'no');
  }
}

Using instanceof for Objects

When unknown might be a class instance, use instanceof:

function handleError(error: unknown) {
  if (error instanceof Error) {
    // Now error is typed as Error
    console.error(error.message);
  } else {
    console.error('Unknown error occurred');
  }
}

Custom Type Guards for Object Shapes

For plain objects, write type predicates to check structure:

type User = { name: string; age: number };

function isUser(value: unknown): value is User {
  return (
    typeof value === 'object' &&
    value !== null &&
    'name' in value &&
    'age' in value
  );
}

function greetUser(data: unknown) {
  if (isUser(data)) {
    // data is now typed as User
    console.log(`Hello, ${data.name}!`);
  }
}

The Pattern: Check, Then Use

Think of narrowing unknown like opening a mystery package: you must inspect it (type guard) before safely using the contents inside.

Key Takeaway: Always narrow unknown with typeof, instanceof, or custom type predicates before using its value—this maintains type safety while handling dynamic data.