Categories
TypeScript Answers

How to use enums inside a class with TypeScript?

Spread the love

Sometimes, we want to use enums inside a class with TypeScript

In this article, we’ll look at how to use enums inside a class with TypeScript.

How to use enums inside a class with TypeScript?

To use enums inside a class with TypeScript, we can put it in the same module as the class.

For instance, we write

enum State {
  STATE_IDLE,
  STATE_LOADING,
  STATE_READY,
  STATE_ERROR,
}

export class Image {
  constructor() {}
  public static readonly State = State;
}

to add the Image class that has the static State variable set to the State enum.

Then we can use it with Image.State.

Conclusion

To use enums inside a class with TypeScript, we can put it in the same module as the class.

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 *