runtime.boot

Full Stack Systems
Production Mindset

CodeWithMihir

Engineering thoughtful products from interface to infrastructure.

CodeWithMihir

TypeScript Tutorial

TypeScript unknown Type Explained with Examples

Learn the TypeScript unknown type, how it differs from any, and how to safely narrow unknown values before using them.

Welcome back! I am Mihir, and in this lesson we will learn the unknown type in TypeScript.

unknown means a value can be anything, but TypeScript will not let you use it until you check what it is.


What is unknown?

let value: unknown = "TypeScript";

value = 25;
value = true;
value = { name: "Mihir" };

Like any, unknown can store any value.

But unlike any, you cannot freely use it.


unknown Is Safer Than any

With any:

let value: any = "hello";

value.toFixed(2);

TypeScript allows it, even though a string does not safely support toFixed().

With unknown:

let value: unknown = "hello";

value.toFixed(2);

TypeScript warns because it does not know whether value is a number.


Narrow unknown with typeof

Use typeof before using an unknown value.

function printValue(value: unknown): void {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  }

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

Inside each if block, TypeScript knows the narrowed type.


Narrow unknown Objects

Objects need a little more care.

function isUser(value: unknown): value is { name: string } {
  return (
    typeof value === "object" &&
    value !== null &&
    "name" in value &&
    typeof value.name === "string"
  );
}

function printUser(value: unknown): void {
  if (isUser(value)) {
    console.log(value.name);
  }
}

The isUser function is a type guard. We will study type guards more deeply later.


unknown with API Data

Data from outside your app is not guaranteed to match your expectations.

async function loadData(): Promise<unknown> {
  const response = await fetch("/api/user");
  return response.json();
}

After loading it, validate it before use:

const data = await loadData();

if (isUser(data)) {
  console.log(data.name);
}

This is much safer than typing external data as any.


unknown with Error Handling

In modern TypeScript, caught errors are often treated as unknown.

try {
  throw new Error("Something went wrong");
} catch (error: unknown) {
  if (error instanceof Error) {
    console.log(error.message);
  }
}

This is safer because JavaScript can throw anything, not only Error objects.


Assigning unknown

You can assign any value to unknown.

let value: unknown;

value = "text";
value = 100;
value = false;

But you cannot assign unknown to a specific type without checking.

let name: string;
let value: unknown = "Mihir";

name = value;

TypeScript warns.

Correct:

if (typeof value === "string") {
  name = value;
}

unknown vs any

TypeCan Store AnythingCan Use Without CheckingSafety
anyYesYesLow
unknownYesNoHigh

Use unknown when the value is uncertain.

Use a specific type when you already know the shape.


Common Mistake: Using Type Assertion Too Early

const user = value as { name: string };

console.log(user.name);

This tells TypeScript to trust you, but it does not validate the runtime value.

Prefer a check:

if (isUser(value)) {
  console.log(value.name);
}

Quick Reference Summary

ConceptExample
Unknown variablelet value: unknown
String narrowingtypeof value === "string"
Number narrowingtypeof value === "number"
Error narrowingerror instanceof Error
Object checktypeof value === "object" && value !== null
Safer than anyRequires checking before use

Practice

Create a function that accepts unknown input:

function printLength(value: unknown): void {
  if (typeof value === "string") {
    console.log(value.length);
    return;
  }

  console.log("Value is not a string");
}

Try calling it with a string, number, boolean, and object.


What You've Learned

You now understand:

  • What unknown means
  • Why unknown is safer than any
  • How to narrow unknown values
  • How unknown helps with API data
  • How unknown works in error handling
  • Why type assertions do not validate data

What's Next?

In the next lesson, we will learn the never Type in TypeScript.

We will see how TypeScript represents impossible values and unreachable code.


Need Help?

  • Have questions, confusion, or want to know more? Contact me

unknown is TypeScript's polite way of saying: check first, then use.