Fewv Minutes of Union Type in Typescript

» Union Type in TypeScript

  1. In TypeScript, a union type allows a variable to have multiple possible types. It allows us to declare that a variable or parameter can have a value of one of two or more different types.

  2. Union types are represented using the pipe (|) operator. To declare a union type, we list the types separated by the pipe operator. Here’s an example:

let age: number | string;
  1. In this example, the age variable can have a value of either a number or a string. We can assign a value of either type to the variable.

  2. Let’s initialize it here:

age = 25; // valid
console.log("My age is " + age);
  1. Our output would be like this in console:

Console:

My age is 25
  1. This is also valid:
age = "thirty"; // valid
console.log("My age is " + age);
  1. Our output would be like this in console:

Console:

My age is thirty

» More Example of union type

  1. Here are some more examples of using union types in TypeScript:

  2. In this example, the printId function takes an parameter id that can be either a number or a string.

function printId(id: number | string) {
  console.log("ID:", id);
}

printId(101); // valid
printId("ABC"); // valid

Console:

ID: 101
ID: ABC

» toString() method.

  1. In this example which is similar to previous one, we don’t know which type it is in the function body, but we can still use toString() method because both types have access toString() method.
function printId(code: string | number) {
  console.log(`My id is ${code.toString()}.`);
}
printId(404); //vaild
printId("404"); //vaild

Console:

My id is 404.
My id is 404.

» Union Type Error toUpperCase() method

  1. In this example we will get an error because toUpperCase() is a string method and the number type doesn’t have access to it.
function printID(code: string | number) {
  console.log(`My id is ${code.toUpperCase()}.`);
  // error: Property 'toUpperCase' does not exist ontype 'string | number'.
  //Property 'toUpperCase' does not exist on type 'number'
}

I hope this cleared - What is Union type? and where can we get an error in it. Thank You!!😊