3

Convert a JavaScript Enum to a String

 1 year ago
source link: https://masteringjs.io/tutorials/fundamentals/enum-to-string
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Convert a JavaScript Enum to a String

Feb 20, 2023

The standard pattern for JavaScript enums is the following.

const Direction = {
  Up: 'Up',
  Down: 'Down',
  Left: 'Left',
  Right: 'Right'
};

TypeScript enums compile to almost the above JavaScript, so everything in this post also applies to TypeScript enums.

enum Direction {
  Up,
  Down,
  Left,
  Right
}

Converting an Entire Enum to a String

Enums are just objects, so JSON.stringify() works for converting an enum to a string.

// {"Up":"Up","Down":"Down","Left":"Left","Right":"Right"} in JavaScript
// {"0":"Up","1":"Down","2":"Left","3":"Right","Up":0,"Down":1,"Left":2,"Right":3} in TypeScript
console.log(JSON.stringify(direction));

Converting TypeScript Enum Values to Strings

In TypeScript, enum values are numbers.

console.log(Direction.Up); // 0

TypeScript enums also store a mapping from the numeric value back to the string, so to convert the numeric enum value back to a string do the following.

console.log(Direction[Direction.Up]); // 'Up'

More Fundamentals Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK