Categories
TypeScript Answers

How to cast int to enum strings in TypeScript?

Spread the love

Sometimes, we want to cast int to enum strings in TypeScript.

In this article, we’ll look at how to cast int to enum strings in TypeScript.

How to cast int to enum strings in TypeScript?

To cast int to enum strings in TypeScript, we can use numbers to access the enum values unless we assign the enum to different values.

For instance, we write

export enum Type {
  Info,
  Warning,
  Error,
  Fatal,
}

const x = Type[0];

to create the Type enum.

Then we can get 'Info' by using Type[0] since the first entry of an enum has 0 assigned to it as its value by default.

Conclusion

To cast int to enum strings in TypeScript, we can use numbers to access the enum values unless we assign the enum to different values.

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 *