how to merge two types in typescript

index.ts
type Type1 = {
  prop1: string;
  prop2: number;
};

type Type2 = {
  prop3: boolean;
  prop4: string[];
};

// Merging two types using '&' operator
type MergedType = Type1 & Type2;

const obj: MergedType = {
  prop1: 'hello',
  prop2: 42,
  prop3: false,
  prop4: ['world']
};
278 chars
20 lines

In the example above, we declare two object types Type1 and Type2. We want to combine them into a single type, so we'll use the & operator to create a type intersection.

The resulting type MergedType will have all the properties and their types from both Type1 and Type2. We can then create an object of MergedType and assign values to its properties.

TypeScript also offers type unions, which is another approach to combining two or more types.

index.ts
type Type1 = {
  prop1: string;
  prop2: number;
};

type Type2 = {
  prop3: boolean;
  prop4: string[];
};

// Merging two types using '|' operator
type MergedType = Type1 | Type2;

const obj: MergedType = {
  prop1: 'hello',
  prop2: 42,
};
243 chars
18 lines

In this example, we declare a type union using the | operator. The resulting type MergedType can contain values that have either the properties and types of Type1 or Type2.

Note that in the latter case, we can create an object containing only prop1 and prop2, but not prop3 and prop4.

gistlibby LogSnag