UNIONS | Unions | unions

A union type in TypeScript allows a variable to hold values of more than one distinct type. This is useful in situations where the exact type of the value isn't known in advance but is limited to a specific set of possible types.

For example, consider a case where you're receiving a value from an API, and this value could either be a number or a string. Since the type is not fixed but can be one of those two, you can define the variable using a union type like this:

image.png

let subcribers: number | string = 10;
subcribers = 100000;
subcribers = "1million";

Another thing that will surprise you in TypeScript is the ability to define literal value types.

Let’s say you’re handling the status of a network request. Typically, the status can only be one of three specific values: "pending" , "success" , or “error". Instead of allowing any string, TypeScript lets you restrict the variable to accept only those exact values.

image.png

This helps prevent accidental mistakes and gives you better autocomplete and type checking.

So yes , TypeScript can enforce not just the type, but even the exact value you’re allowed to use.

Note The order of a union type declaration does not matter. You can write boolean | number or number | boolean and TypeScript will treat both the exact same.

Any Type

TypeScript has a special any type that can be used to represent any type. When a variable is annotated with the any type, TypeScript will allow it to have any value and disable all type checking for that variable and its properties.

Warning

While the any type can be helpful in some situations—such as when gradually migrating a codebase to TypeScript—it should be used with caution. Overusing any effectively disables TypeScript’s type-checking for that value, turning your typed code into untyped JavaScript. This increases the risk of runtime errors and makes it harder to catch bugs during development.

Whenever possible, prefer more specific or safer alternatives like union types, unknown, or well-defined interfaces. This allows you to take full advantage of TypeScript’s static analysis and build more reliable, maintainable code.