TypeScript Union Types: A Complete Guide for Beginners

What is union in TypeScript?

A union type in TypesScript represents a value of multiple types. It is like a TypeScript tuple.

However, in union type, we must use the vertical bar ( | ) to distinguish between each type.

So, if we write number | string | boolean, it means the value could be a number, a string, or a boolean.

TypeScript Union Types

In TypeScript, there’s a concept called “union types”. This is a way to say that a variable or function can handle more than one type of data.

Syntax:

(type1 | type2 | type3 | .. | typeN)

Union Type Variable

You might have a variable that could be either a string or a number.

For example:

let sampleVariable: string | number;

// Assigning a number to the variable
sampleVariable = 8;
console.log(sampleVariable); // Outputs: 8

// Assigning a string to the variable
sampleVariable = "Hi, Welcome to Itsourcecode!";
console.log(sampleVariable); // Outputs: Hi, Welcome to Itsourcecode!

As you can see, sampleVariable could be assigned a string or number value.

You can test the above example here! ➡TyspeScript Online Compiler

Output:

8
Hi, Welcome to Itsourcecode!

Union Type and function parameter

Similarly, you might have a function that accepts a parameter that could be a string or a number.

For example:

function display(input: string | number) {
  if (typeof input === "string") {
    console.log(`The input is a string: ${input}`);
  } else {
    console.log(`The input is a number: ${input}`);
  }
}

display("Hi, welcome to Itsourcecode!");
display(100000000);

You can test the above example here! ➡TyspeScript Online Compiler

In this function, the parameter could be passed as a string or a number.

Output:

The input is a string: Hi, welcome to Itsourcecode!
The input is a number: 100000000

So, in essence, union types in TypeScript are a way to handle variables or functions that can work with multiple types of data.

It’s a flexible and powerful feature of the language.

Union Type and Arrays

You can use union types with arrays, properties, and interfaces too.

Here’s an example with an array:

let samplearray;
let i;
samplearray = [1, 2, 3, 4, 5];
console.log("Number Array:");

for (i = 0; i < samplearray.length; i++) {
   console.log(samplearray[i]);
}

console.log(); // This is just spacing

samplearray = ["Programming", "Math", "English", "Software Development", "Web Development"];
console.log("String Array:");

for (i = 0; i < samplearray.length; i++) {
   console.log(samplearray[i]);
}

As you can see in our given example, the program makes an array. This array can hold either numbers or strings.

Output:

Number Array:
1
2
3
4
5

String Array:
Programming
Math
English
Software Development
Web Development

What is the discriminated union type in TS?

In TypeScript, there’s something called a “discriminated union type”.

It’s a special type of union type that uses a shared property (called the “discriminant”) to tell the difference between the types it can be.

This is useful when you’re dealing with data that can change forms but still belongs to the same group.

For example:

type Animal = 
    | { type: "dog"; name: string }
    | { type: "cat"; name: string };

function greet(animal: Animal) {
    switch (animal.type) {
        case "dog":
            return "Woof! I'm " + animal.name;
        case "cat":
            return "Meow! I'm " + animal.name;
    }
}

let dog: Animal = { type: "dog", name: "Happiness" };
let cat: Animal = { type: "cat", name: "Ecstatic" };

console.log(greet(dog)); 
console.log(greet(cat)); 

Output:

Woof! I'm Happiness
Meow! I'm Ecstatic

Conclusion

A union type in TypeScript is a way to handle variables or functions that can work with multiple types of data.

For example, a variable could be either a string or a number. This is represented as string | number in TypeScript.

This concept is flexible and powerful and can be used with arrays, properties, and interfaces too.

I hope that this article helps you understand the TypeScript Union Types.

If you have any questions or inquiries, please don’t hesitate to leave a comment below.

Leave a Comment