How to combine members of multiple types in a TypeScript annotation?

Sometimes, we want to combine members of multiple types in a TypeScript annotation.

In this article, we’ll look at how to combine members of multiple types in a TypeScript annotation.

How to combine members of multiple types in a TypeScript annotation?

To combine members of multiple types in a TypeScript annotation, we can create union types.

For instance, we write

interface ClientRequest {
  userId: number;
  sessionKey: string;
}

interface Coords {
  lat: number;
  long: number;
}

type Combined = ClientRequest | Coords;

to create the Combined type which is an union of the ClientRequest and Coords interfaces.

This means the members of any object with the Combined type should be either from the ClientRequest or the Coords interfaces.

Conclusion

To combine members of multiple types in a TypeScript annotation, we can create union types.