DEV Community

Anik Deb Nath
Anik Deb Nath

Posted on

Union and intersection type in Typescript

Union and intersection type in Typescript blog by anik deb nath
Union:

In typescript we can use union type when we need to use more than a single type. We can also say that union means “OR”. To use union type we can use pipe (‘|’) symbol as union type. By this type we can also combine multiple data types in typescript. Let’s see union type’s syntax below:

const checkNum : number | string ; 
checkNum = 10; 
checkNum = "Hello"; 
checkNum = true; // give here error becasue checkNum value should be number or string.
Enter fullscreen mode Exit fullscreen mode

So here we see that myNum can be number or string which is provide more flexibility in our code.

Use Union as function parameters:

const sayHi = (param:string | number) => {
 return console.log(param);
}
sayHi("Hello!")
sayHi(89.6)
sayHi(true) //Argument of type 'boolean' is not assignable to parameter of type 'string | number'.
Enter fullscreen mode Exit fullscreen mode

Union of Literal Types:

we can declare a union type including of literal types, such as string literals, number literals or boolean literals etc. Example :

type Sports = 'cricket' | 'football' | 'tenis';
function watchMovie(game: Sports) {
    console.log(`You are playing ${game}.`);
}
watchMovie('cricket');
watchMovie('football');
Enter fullscreen mode Exit fullscreen mode

This will make our code more type-safe and error-free, and help us to avoid unnecessary type checks or type assertions.

Intersection:

Intersection type is allowing us to combine multiple types into a single type with all of the properties. We must use “&” and operator to create intersection type in typescript. Let’s see union type’s syntax below:

type Name = variable_1 & variable_2;
let var: variable_3;
Enter fullscreen mode Exit fullscreen mode

Intersection can Combine interface:

In typescript we can define a type by combining two different interface using intersection that means type can get all properties of both interfaces. Let’s see the example below:

interface Student{
    name: string;
    age: number;
    stdId: number;
}
interface Teacher{
    teachingId: string;
}
type User = Student & Teacher;
User.age = 5;
User.teachingId ="CSE123";
User.name = 'Karim';
Enter fullscreen mode Exit fullscreen mode

Here the order of the types in an intersection does not concern. Suppose Student & Teacher is equivalent to Teacher & Student.

Use intersection types to extend or override existing types

Let’s see an example:

type area = {
  width:string;
  height:string;
};
type volume = area & { depth: string };
Enter fullscreen mode Exit fullscreen mode

In short union and intersection types in TypeScript:

Union

  • Can combine one or more types into one type.
  • By using the pipe ‘|’ operator, we can perform union.
  • Example: type value = string | number;

In functions or variables, union types are useful for accepting various types of values.

Intersection

  • Can merge properties from one or more types.
  • By using the ampersand ‘&’ operator, we can perform intersection.
  • Example: type User = Student & Teacher;

In composing types and enforcing strict type contracts, intersection types are useful.

Summary:

In summary we can say that union types provide versatility by allowing variables to hold values from many types, whereas intersection types combine numerous types into a single, more exact type. Depending on the needs of our code, we may opt to utilize union types to handle a variety of data circumstances or intersection types to compose exact type structures and execute strict type contracts.

Top comments (0)