Lesson 19 of 60 – unknown Type
32%

unknown Type in TypeScript

The unknown type is used when a value can be of any type, but TypeScript should not allow us to use that value until we check its actual type.

Note: unknown is safer than any because TypeScript requires type checking before performing most operations on an unknown value.

1. What is the unknown Type?

The unknown type can store a value of any type, just like any.

let value: unknown = "Hello";

The important difference is that TypeScript does not automatically allow operations on an unknown value.

2. Declaring an unknown Variable

Use the unknown keyword after the colon.

let data: unknown;

The variable can later store values of different types.

3. unknown with a String

An unknown variable can store a string.

let value: unknown = "Hello TypeScript";

The value is stored successfully, but its type must be checked before using string-specific methods.

4. unknown with a Number

An unknown variable can also store a number.

let value: unknown = 100;

TypeScript accepts the value because unknown can represent any type.

5. Changing the Value of unknown

An unknown variable can contain different types of values at different times.

let value: unknown = "Hello";

value = 100;

value = true;

All these assignments are allowed.

6. unknown with Boolean

The unknown type can store boolean values.

let status: unknown = true;

status = false;

Both values are valid.

7. unknown with an Array

An unknown variable can store an array.

let data: unknown = [10, 20, 30];

However, you should check the value before performing array-specific operations.

8. unknown with an Object

The unknown type can also contain an object.

let student: unknown = {
    name: "Amit",
    age: 21
};

Before accessing properties, the object should be checked.

9. unknown Requires Type Checking

TypeScript does not allow you to directly use string-specific methods on an unknown value.

let value: unknown = "Hello";

// TypeScript does not allow this directly:
// value.toUpperCase();

First, check whether the value is a string.

10. Using typeof with unknown

The typeof operator can be used to check the type of an unknown value.

let value: unknown = "Hello";

if (typeof value === "string") {
    console.log(value.toUpperCase());
}

Inside the if block, TypeScript knows that the value is a string.

11. Checking for a Number

Use typeof to check whether an unknown value is a number.

let value: unknown = 100;

if (typeof value === "number") {
    console.log(value + 50);
}

The operation is safe after the type check.

12. Checking for a Boolean

You can also check whether an unknown value is a boolean.

let value: unknown = true;

if (typeof value === "boolean") {
    console.log(value);
}

13. Checking for an Object

The typeof operator returns "object" for objects.

let value: unknown = {
    name: "Amit"
};

if (typeof value === "object" && value !== null) {
    console.log("This is an object");
}

The null check is useful because typeof null is also "object".

14. unknown and Type Narrowing

Checking an unknown value and reducing it to a more specific type is called type narrowing.

let value: unknown = "Hello";

if (typeof value === "string") {
    console.log(value.length);
}

After the check, TypeScript narrows the type to string.

15. unknown as a Function Parameter

A function parameter can be declared as unknown.

function show(value: unknown) {
    console.log(value);
}

show("Hello");
show(100);
show(true);

The function accepts values of different types.

16. Checking unknown Inside a Function

You can safely work with an unknown parameter after checking its type.

function show(value: unknown) {

    if (typeof value === "string") {
        console.log(value.toUpperCase());
    }

}

17. unknown and Arrays

When an array is stored as unknown, check whether the value is an array before using it.

let data: unknown = [10, 20, 30];

if (Array.isArray(data)) {
    console.log(data.length);
}

Array.isArray() helps identify arrays.

18. unknown and API Responses

The unknown type is useful when receiving data from an API whose structure has not yet been verified.

let response: unknown;

response = {
    name: "Rahul",
    age: 22
};

The data should be checked before it is used.

19. unknown vs any

Both types can hold values of different types.

let a: any = "Hello";
let b: unknown = "Hello";

The difference is that any allows operations without type checking, while unknown requires appropriate checks.

20. Why unknown is Safer

unknown helps prevent accidental operations on values whose types are not known.

let value: unknown = 100;

// TypeScript prevents unsafe operations
// until the type is checked.

This provides an additional layer of type safety.

21. Type Assertion with unknown

Sometimes you know the actual type of an unknown value. You can use a type assertion.

let value: unknown = "Hello";

let message = value as string;

console.log(message.toUpperCase());

The as string syntax tells TypeScript how you intend to treat the value.

22. Type Assertion with Numbers

An unknown value can also be asserted as a number.

let value: unknown = 100;

let numberValue = value as number;

console.log(numberValue + 50);

The assertion tells TypeScript to treat the value as a number.

23. unknown with React

In React applications, unknown can be useful when data comes from an external source and its structure has not yet been verified.

const data: unknown = getData();

The data can be checked before displaying it in a component.

24. unknown with React Native

React Native applications can receive data from APIs, storage, navigation parameters, or other external sources.

const userData: unknown = getUserData();

Checking the value before using it helps make the application safer.

25. unknown and User Data

Suppose user information comes from an external source.

let user: unknown = {
    name: "Amit",
    age: 21
};

Before accessing properties, the value should be checked or narrowed to a known structure.

26. Common Mistake with unknown

A common mistake is trying to use an unknown value directly without checking its type.

let value: unknown = "Hello";

// Not allowed directly:
// console.log(value.toUpperCase());

First perform a type check or use a valid type assertion.

27. unknown for Safer External Data

External data can have an unexpected structure. Using unknown encourages you to validate the data before using it.

let data: unknown = receiveData();

if (typeof data === "string") {
    console.log(data);
}

28. unknown vs Specific Types

If you already know the type of a value, use a specific type instead of unknown.

let name: string = "Rahul";
let age: number = 20;
let active: boolean = true;

Use unknown when the type is genuinely not known yet.

29. Practical Example

Here is a simple example where the value may be a string or a number.

let value: unknown = "Hello";

if (typeof value === "string") {
    console.log("String:", value);
}

if (typeof value === "number") {
    console.log("Number:", value);
}

The program checks the value before using it.

30. unknown Type Summary

The unknown type can store values of any type, but TypeScript requires you to check the value before performing most operations.

let value: unknown = "Hello";

if (typeof value === "string") {
    console.log(value.toUpperCase());
}

This makes unknown a safer alternative to any when the actual type is not known.

📌 Key Points

  • unknown can store values of any type.
  • It is safer than any.
  • Type checking is required before using an unknown value.
  • The typeof operator is commonly used with unknown.
  • Array.isArray() can be used to identify arrays.
  • Type narrowing makes an unknown value more specific.
  • Type assertions can be used when you know the actual type.
  • unknown is useful for external and API data.
  • Use specific types when the type is already known.

🧠 Quick Quiz

Question: Why is unknown safer than any?