DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Union & intersection types in TS

In TypeScript, union types and intersection types are ways to combine multiple types to create new types with specific characteristics.
Union Types (|):

A union type allows a variable to have one of several types. It is represented using the | symbol.

// Union type
type MyType = string | number;

let value: MyType;
value = "Hello"; // Valid
value = 42;      // Valid
// value = true; // Error: Type 'boolean' is not assignable to type 'string | number'.

Enter fullscreen mode Exit fullscreen mode

Intersection Types (&):

An intersection type combines multiple types into one, allowing an object to have all properties from each type. It is represented using the & symbol.

// Intersection type
type Point2D = { x: number; y: number };
type Point3D = { z: number };

type Point = Point2D & Point3D;

const point: Point = { x: 1, y: 2, z: 3 };

Enter fullscreen mode Exit fullscreen mode

Union Types vs. Intersection Types:

Union Types:
    Represents a value that can be one of several types.
    Uses the | symbol.
    The value can be of any type in the union.

Intersection Types:
    Represents a value that has all properties of multiple types.
    Uses the & symbol.
    The value must have all the properties of all types in the intersection.
Enter fullscreen mode Exit fullscreen mode

Example of Using Both:

type A = { foo: number };
type B = { bar: string };

// Union type
type UnionType = A | B;
let unionValue: UnionType;

unionValue = { foo: 42 };  // Valid
unionValue = { bar: "hello" };  // Valid
// unionValue = { foo: 42, bar: "hello" };  // Error: Object literal may only specify known properties, and 'bar' does not exist in type 'A'.

// Intersection type
type IntersectionType = A & B;
let intersectionValue: IntersectionType;

intersectionValue = { foo: 42, bar: "hello" };  // Valid
// intersectionValue = { foo: 42 };  // Error: Property 'bar' is missing in type '{ foo: number; }' but required in type 'B'.


Enter fullscreen mode Exit fullscreen mode

Top comments (0)