JavaScript

How Does unknown Protect Your TypeScript Code?

Learn how TypeScript's unknown type protects your code from runtime errors. Understand unknown vs any, type narrowing, and practical examples of writing safer TypeScript code.

M
Md Shayon
Nov 15, 2026
6 min read
Table of Contents
How Does unknown Protect Your TypeScript Code?

Have you ever written some code that looked perfectly fine but crashed when you ran it?

Well, sometimes the problem comes from a small TypeScript mistake. One common example is using any. The any type lets you do almost anything with a value. Sounds useful, right? But there's a catch. It can also hide mistakes that TypeScript would normally catch. Luckily, TypeScript has a better option: unknown. Both any and unknown can hold any type of value. But they work very differently. Let's see why unknown is safer and how it can help you write better TypeScript code. The TypeScript documentation describes unknown as the type-safe counterpart of any.

The Problem with any

Let's start with a simple example. Imagine you have a function that takes a value and converts it to uppercase.

function processAny(value: any) {
  return value.toUpperCase();
}
const result = processAny(123);
console.log(result);

Looks fine, doesn't it? But there's a problem. We're passing 123 to the function. That's a number, not a string. Numbers don't have a toUpperCase() method. So, when JavaScript runs this code, it throws an error.

TypeError: value.toUpperCase is not a function

But wait. Why didn't TypeScript catch this mistake? Because we used any. When you use any, you're basically telling TypeScript: "Don't worry about this value. I'll handle it myself." So, TypeScript stops checking what you do with that value. For example:

let value: any = "Hello";
value.toUpperCase();
value.toFixed();
value.someRandomMethod();

TypeScript allows all three lines. But not all of them will work when the code runs. That's the problem with any. It makes it easy to write code that looks correct but can fail later.

Read article on "TypeScript Types vs Interfaces"

Meet unknown: A Better Option

Now, let's try the same example with unknown.

function processUnknown(value: unknown) {
  return value.toUpperCase();
}

This time, TypeScript shows an error. Why? Because TypeScript doesn't know what kind of value we're receiving. It could be a string, a number, an object, or something else. And honestly, that's a good thing. Instead of allowing us to use the value without checking it, TypeScript asks us to make sure it's safe first. That's what makes unknown different. Both any and unknown can hold any value. But unknown doesn't let us use that value until we check its type.

Read article on "Cut API Response Time by 60% With gRPC"

How to Use unknown Safely

So, how do we fix the error? Simple. We check the value before using it. Let's update our function.

function processUnknown(value: unknown) {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return "This is not a string!";
}

Let's break it down. First, we accept an unknown value.

function processUnknown(value: unknown) {

We don't know what the function will receive. So, instead of guessing, we use unknown. Next, we check its type.

if (typeof value === "string") {

Here, typeof checks whether the value is a string. If it is, TypeScript understands that we have a string inside this block. This is called type narrowing. In simple words, we're checking what a value actually is before using it. Now, we can safely call toUpperCase().

return value.toUpperCase();

Why does this work now? Because we've already checked that the value is a string. TypeScript knows it's safe to use the string method. Finally, we handle other values.

return "This is not a string!";

What if someone passes a number? No problem. Our function handles it instead of trying to call a method that doesn't exist. Let's test it.

console.log(processUnknown("hello"));
// HELLO
console.log(processUnknown(123));
// This is not a string!

See the difference? We checked the value first. Then we used it. That's exactly how unknown helps protect your code.

Read article on "Stop Ignoring Cloud Costs Before They Explode"

any vs unknown: What's the Difference?

Let's put them side by side.

Feature

any

unknown

Can hold any value

Yes

Yes

Allows direct method calls

Yes

No

Requires type checking

No

Yes

Helps prevent mistakes

No

Yes

Keeps type safety

No

Yes, with type checks

Here's another small example.

let valueAny: any = 123;
let valueUnknown: unknown = 123;

// TypeScript allows this
console.log(valueAny.toUpperCase());

// TypeScript shows an error
// console.log(valueUnknown.toUpperCase());

Both variables contain the same number. But TypeScript treats them differently. Think about it this way:

  • any says: "Trust me. I know what I'm doing."

  • unknown says: "Hold on. Check what this value is first."

And that's the whole idea.

Read article on "10 Next.js Security Mistakes"

Where Should You Use unknown?

Now you might be thinking, "Okay, this makes sense. But where would I actually use it?" Good question. There are several places where unknown can be really useful.

API Responses

Imagine you're getting data from an API.

async function fetchData(): Promise<unknown> {
  const response = await fetch("/api/users");

  return response.json();
}

Here, fetch() sends a request to the API, and response.json() reads the returned JSON data. But do we know exactly what the API will return? Not always. Maybe the API returns the expected user data. Maybe something goes wrong. Maybe the response has a different structure. That's why unknown is a good starting point. Before using the data, check whether it has the structure you expect.

User Input

Think about a registration form. A user can enter an email, a phone number, or even something completely unexpected. You shouldn't blindly trust incoming data. Using unknown at the right place helps you remember to check the value before working with it.

Error Handling

Here's another useful example.

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

Why use unknown here? Because JavaScript allows you to throw different kinds of values, not just Error objects. The instanceof check helps us make sure that the caught value is an actual Error before accessing its message. Simple, but useful!

Read article on "Adding a Vector Database"

A Few Tips to Remember

Before we finish, here are a few things worth remembering. Use unknown instead of any: When you don't know the type of a value, start with unknown. Check before using: Use typeof, instanceof, or other type checks. Don't blindly trust API data: Always check external data before using it. Avoid unnecessary type assertions: Writing value as string doesn't actually check whether the value is a string. It only tells TypeScript to trust you. Enable strict mode: Set "strict": true in your tsconfig.json to catch more type-related mistakes. One more thing: unknown doesn't magically check your data at runtime. It helps TypeScript stop unsafe operations while you're writing code. You still need proper checks to make sure the data is valid.

Summary

So, what's the real difference between any and unknown? Both can hold any kind of value. But any lets you use that value without checking it. That's why it can hide mistakes and cause runtime errors. unknown takes a different approach. It asks you to check the value before using it. And that's exactly why it's safer.

Tags

# TypeScript# TypeScript Unknown# TypeScript Any vs Unknown# TypeScript Type Safety# Type Narrowing# TypeScript Type Guards# JavaScript# TypeScript Tutorial
Keep Reading

Related Articles

Continue your learning journey