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

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...

Sending the id from a component to a service in Angular

In my current project, I am working on a chat application using Angular with WebSocket integration. Let me provide an overview of the architecture I have designed for this project. I created a module called 'chatting' which contains a list of use ...

Handling Click and Mouse Events with React [react-sortable-hoc, material-ui, react-virtualized]

I have come across an interesting example that I would like to share with you. Check out this live working example on Stackblitz When the delete button on the red bin icon is pressed, the onClick event handler does not get triggered (sorting happens inst ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

Exploring ways to interact with an API using arrays through interfaces in Angular CLI

I am currently utilizing Angular 7 and I have a REST API that provides the following data: {"Plate":"MIN123","Certifications":[{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"KIO","Date":"12-02-2018","Number":1},{"File":"preventive","StartDate":"06 ...

Utilizing HTML and Ionic 3.x: Implementing a for loop within the HTML file by utilizing "in" instead of "of"

I am working with multiple arrays of objects in my typescript file and I need to simultaneously iterate through them to display their contents in the HTML file. The arrays are always the same size, making it easier to work with. Here is what I currently ha ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

Can a mapped union type be created in TypeScript?

Can the features of "mapped types" and "union types" be combined to generate an expression that accepts the specified interface as input: interface AwaActionTypes { CLICKLEFT: 'CL'; CLICKRIGHT: 'CR'; SCROLL: 'S'; ZOOM ...

How can we define a function using a generic type in this scenario using Typescript?

Here's a challenge that I'm facing. I have this specific type definition: type FuncType<T> = (value: T) => T I want to create a function using this type that follows this structure: const myFunc: FuncType<T> = (value) => valu ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

having difficulty interpreting the information from angular's httpclient json request

After creating an Angular function in typescript to make an http request for JSON data and save it to an object, I noticed that the function requires two clicks of the associated button to work properly. Although the connection and data parsing are success ...

Exploring the capabilities of SWR for updating data in Next JS

I have been working on creating a component with an active property that can be toggled by the user as many times as they want. Since I am using Next.js, I decided to implement SWR for client-side rendering. However, despite my efforts over the past few da ...

Transform the property of type any/unknown into a specific generic type T within the map

Suppose I start with... type TypeNonGeneric = { prop1: any, prop2: string }; How do I transform it into... type TypeGeneric<T> = { prop1: T, prop2: string }; I have reviewed the documentation and it appears that I need to create a new generic type ...

Array of options with specified data types in Props interface

Trying to implement options as props for styling a button component in Astro. Still learning TypeScript. Encountering the error message: Generic type 'Props<style>' requires 1 type argument(s). Below is the code snippet: --- import type { H ...

Unable to access specific data from the JSON string retrieved from the backend, as it is returning a value of undefined

After receiving a JSON string from the backend, my frontend is encountering issues when trying to index it post using JSON.parse(). The indexed value keeps returning as undefined, even though it's a JSON object literal and not within an array. For th ...

best typescript configuration for node 8 suggested

When configuring TypeScript for use with Node 8, what is the optimal setup? Many tutorials recommend using the following tsconfig.json: { "compilerOptions": { "target": "es6", "module": "commonjs" } } However, it has come to my attention tha ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Customizing MUI Themes with TypeScript: How do I inform TypeScript that the theme is provided by the provider?

Below is a modified demo code snippet extracted from Material UI documentation: function ThemeUsage() { const theme = { palette: { primary: { main: "#000", }, }, } as const; type DefaultThemeType = { theme: type ...

Creating an interface for writing types in Firebase functions/storage/database

What are the TypeScript types for Firebase functions, storage, and admin? I'm fairly new to TypeScript and currently in the process of updating my JavaScript code to TypeScript. Within my code, I am generating a context object. const context = { ...