Search This Blog

2023/09/10

Type Union & Intersection in Typescript

 In TypeScript, intersection (&) and union (|) are two different ways to combine types, and they have opposite purposes:


Intersection (&):

Purpose: An intersection type represents a type that has all the properties and methods that are common to all the types being intersected.
Usage: It is used when you want to create a new type that includes all properties and methods from multiple types.

Example:


type TypeA = { propA: number };
type TypeB = { propB: string };
type IntersectionType = TypeA & TypeB;
// IntersectionType contains propA and propB.
Union (|):

Purpose: A union type represents a type that can be one of several types. It allows a value to have a variety of types at different times.
Usage: It is used when a value can have multiple possible types, and you want to express that flexibility.
Example:

type TypeA = { propA: number };
type TypeB = { propB: string };
type UnionType = TypeA | TypeB;
// UnionType can be either TypeA or TypeB.

In summary:

Intersection (&) combines types to create a type that has all properties and methods common to all of them. It narrows down the possibilities to a more specific type.
Union (|) combines types to create a type that can be one of the specified types. It broadens the possibilities to a more flexible type.
These two concepts are often used in different scenarios based on the desired behavior of the types you are working with.







No comments:

Post a Comment