Categories
TypeScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *