Course contentsShow
← TypeScript
Lesson 131 of 1,7963. Basic TypesFree lesson

Using unknown Values Safely

See how you must narrow or assert unknown before performing operations on it.

Using unknown Values Safely

You'll learn: How to actually use a value typed as unknown by narrowing or asserting its type before operations.

The Safety Check Required

Remember how unknown is the type-safe alternative to any? The key difference is that TypeScript won't let you do anything with an unknown value until you prove what type it actually is.

Think of unknown like a locked box. You can receive it and store it, but before you can use what's inside, you must either:

  1. Check what's in it (type narrowing with guards)
  2. Declare what you believe is in it (type assertion)

Narrowing with Type Guards

The safest approach is using type guards to narrow the type:

function processValue(value: unknown) {
  // Can't do this! TypeScript error:
  // value.toUpperCase(); ❌

  // Check the type first:
  if (typeof value === "string") {
    // Now TypeScript knows it's a string
    console.log(value.toUpperCase()); ✅
  }

  if (typeof value === "number") {
    console.log(value.toFixed(2)); ✅
  }
}

Type Assertions (Use Carefully)

You can also assert the type if you're confident:

function handleData(data: unknown) {
  // Assert it's a string
  const text = data as string;
  console.log(text.toUpperCase());
}

Warning: Assertions bypass safety checks. If you're wrong, you'll get runtime errors!

Why This Matters

This forced checking is exactly what makes unknown safer than any. You can't accidentally call methods on values that might not have them. The compiler makes you think about what the value could be.

Key Takeaway: Values typed as unknown require type narrowing (like typeof checks) or type assertions before you can perform operations on them—this enforcement is what makes unknown type-safe.