TS Special Types

TypeScript Special Types

TypeScript includes a few special types that do not exist in plain JavaScript.

These types are designed to handle specific, tricky, or unknown scenarios.

They include any, unknown, never, and void.

Understanding them will make you a much more adaptable and capable developer.


1. The Any Type

The any type completely disables type checking for a specific variable.

It is useful when migrating old JavaScript code, but should generally be avoided.

Using any removes the safety benefits that make TypeScript so powerful.

Any Example:

let data: any = "Could be a string";
data = 42; // Now it is a number
data = true; // Now it is a boolean

// No errors will be thrown! console.log("Final data value:", data);


2. The Unknown Type

The unknown type is a much safer alternative to the any type.

It forces you to perform type checks before you can actually use the variable.

This prevents accidental runtime errors while handling dynamic API data.

Unknown Example:

let safeData: unknown = "Hello";

// You must check the type before using string methods if (typeof safeData === "string") { console.log(safeData.toUpperCase()); }


3. Void and Never

void is used for functions that perform an action but return nothing.

never is used for functions that will literally never finish executing.

This happens when a function throws an error or has an infinite loop.

Void and Never Example:

function logMessage(): void {
  console.log("This returns nothing.");
}

function throwError(): never { throw new Error("This will stop execution!"); }

logMessage();


Exercise

?

Which type completely disables TypeScript's static type checking?


4. Final Thoughts

Use unknown instead of any whenever you possibly can.

Use void strictly for defining your function return types.

Next, let's explore how to create typed Arrays in TypeScript!