Obtain the Enum's Name in TypeScript as a String

I am currently looking for a solution to transform the name of an enum into a string format. Suppose I have the following Response enum, how can I obtain or convert 'Response' into a string? One of my functions accepts any enum as input and requires the name, rather than the type of enum, in order to execute further code.

enum Response 
{
    No = 0,
    Yes = 1
}

Answer №1

Unfortunately, it is not possible to convert an enum name to a string directly because the type information is only stored during compilation. To work around this limitation, you need to pass additional parameters that specify which enum you are using.


However, you can use square brackets to convert numeric enum values to strings and vice versa:

Check out this Fiddle for more

enum YesNo {
    No = 0,
    Yes = 1, 
}

console.log(YesNo[YesNo.Yes]);
console.log(YesNo[YesNo.No]);
console.log(YesNo["Yes"]);
console.log(YesNo["No"]);
console.log(YesNo[1]);
console.log(YesNo[0]);

The resulting code after compilation looks like this:

var YesNo;
(function (YesNo) {
YesNo[YesNo["No"] = 0] = "No";
YesNo[YesNo["Yes"]
})(YesNo || (YesNo = {}));
console.log(YesNo[YesNo.Yes]);
console.log(YesNo[YesNo.No]);
console.log(YesNo["Yes"]);
console.log(YesNo["No"]);
console.log(YesNo[1]);
console.log(YesNo[0]);

Answer №2

Get the first key of an object named Response: Object.keys({ Response })[0]; // 'Response'

Answer №3

Maybe we could try this:

EnumType[EnumValue.option1]

Answer №4

The answer given by @Tukkan was correct, but it lacked the specificity needed. Below is a functional code snippet that directly addresses the original poster's question.

enum Options {
    yes,
    no
}
type EnumType = Record<string, any>
function showEnumName(theEnum: EnumType) {
    const enumName = Object.keys(theEnum)[0] ?? ''
    console.log(enumName)
}
showEnumName({ Options })

Playground Link

Some Important Notes:

  1. The function receives the enum object as a parameter and extracts its name. This contrasts with Tukkan's approach which requires direct access to the literal enum object - something not always feasible for users like the OP.
  2. The indexing [0] may be omitted. Correction: This behavior depends on the tsconfig setting. I adapted it here to avoid compile-time warnings, though this might not be universally recommended.
  3. Properly typing the object passed to the function is crucial to prevent compile-time errors. Using 'any' may introduce vulnerabilities, so ensure the object strictly adheres to enum structure.
  4. If you alter the function to align with Tukkan’s method, the outcome differs as demonstrated here:
function showEnumName(theEnum) {
    const enumName = Object.keys({ theEnum })
    console.log(enumName)
}
showEnumName({ Options })

In this scenario, instead of "Options", the output reads "theEnum". As pointed out by Tukkan, this reveals the variable name holding the data rather than the desired enum name.

If you find this response helpful, kindly upvote @Tukkan's answer as well to credit his contribution. This solution was built upon his insights, and recognition should be shared.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing Json data in a variable within Angular 2: a step-by-step guide

https://i.sstatic.net/2QjkJ.png Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wron ...

Sass Alert: The mixin called roboto-family is missing from the stylesheet. Trace: Problem detected in src/pages/forms/forms.scss at

Greetings, I am diving into the world of Ionic for the first time. Recently, I embarked on a new project in Ionic and decided to integrate a theme. To do so, I copied an .html file, an .scss file, and also created a .ts file. Forms.html <!DOCTYPE html ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Issues with Vite's global import feature not functioning properly in a production build

My current setup involves loading all markdown files within a directory using a glob import. The code snippet below depicts this functionality: const useGetChangelogs = () => { const [changelogs, setChangelogs] = useState<string[]>([]); useEf ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

A secure way to perform a deep update on any type, even if it is completely different from the original

Is there a method to eliminate the as any in the update_substate function? It seems type-safe when directly invoking the update_state function, so it should also be safe when invoked indirectly, right? These functions are meant to be lightweight helpers ...

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

Can you provide details on the capabilities of Appium for webviews on Android devices?

I attempted to utilize the following capabilities { maxInstances: 1, browserName: '', appiumVersion: '1.18.2', platformName: 'android', platformVersion: '10.0', deviceName: 'd ...

Refreshing a page with a 404 error in Angular 2 while in production mode and without the useHash configuration

I've encountered an issue while using Angular 2 without the useHash feature. When trying to visit the URL directly in a browser, I'm getting a 404 not found error. I have searched extensively and attempted various solutions including: Adding L ...

Semantic-ui-react cannot be located by Docker

I am a beginner when it comes to docker and I'm looking to create a React app, specifically using TypeScript, inside a docker container. In order to do this, I need to incorporate semantic-ui-react into my project. I followed the instructions provide ...

Error message: The property 'data' is not recognized within this context. Additionally, the property 'datatime' does not exist on the current type

I'm currently working on generating a graph using Firestore data and ng2charts. However, when I run my code, I encounter the following errors: Property 'data' does not exist on type 'unknown', causing an error in item.data Simila ...

Decode Jackson - a process to extract and translate multiple base enums from

Can enums with a one-based index be deserialized successfully? enum Status { Active, Inactive } The value {status:1} should correspond to Status.Active, but Jackson is incorrectly mapping it to Status.Inactive. ...

Using variables to replace 'placeholders' in Typescript with string interpolation

Seeking a definitive answer on this matter, I pose the question: In C#, an example of which would be as follows: var text = "blah blah"; var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah' How can I accomplish t ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

How to extract multiple literals from a string using Typescript

type Extracted<T> = T extends `${string}${'*('}${infer A}${')+'}${string}${'*('}${infer A}${')+'}${string}` ? A : never type Result1 = Extracted<'g*(a12)+gggggg*(h23)+'> // 'a12' | &a ...

Navigating through JSON object using Angular 2's ngFor iterator

I want to test the front end with some dummy JSON before I write a service to get real JSON data. What is the correct way to iterate through JSON using ngFor? In my component.ts file (ngOnInit()), I tried the following code with a simple interface: var js ...

Sorting array of arrays in TypeScript and Node.js involves defining the arrays and then applying a sorting algorithm

Recently delved into TypeScript with limited JavaScript knowledge just a couple of weeks ago. I am attempting to scan through all the files in a particular directory, gather each file name (string) and modification time (number>), then organize them in ...

When additional lines are drawn elsewhere on the HTML5 Canvas, the diagonal lines will gradually appear thicker and more pronounced

For horizontal and vertical lines, using a translation of 0.5 for odd stroke widths results in crisper and sharper lines. But what about diagonal lines? Link to jsfiddle <!DOCTYPE html> <html lang="en"> <body style="background: black"& ...

Combining Layouts and Providers: A Guide to Using Both on a Single Page

I am facing an issue with my provider that is responsible for refreshing a token by making a request to the server. Additionally, I have a basic layout featuring a sidebar that I want to use only on a specific route. However, I am unsure about where to add ...

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...