Retrieve all values of a specific enum type in TypeScript

When working with Typescript, I am looking to retrieve all values of an enum type and store them in an array. In C#, a similar method would look like this:

public static TEnum[] GetValues<TEnum>() where TEnum : Enum
{
    return Enum.GetValues(typeof(TEnum))
        .OfType<TEnum>()
        .ToArray();
}

How can we achieve the same functionality in Typescript? Ideally, the usage would resemble:

const allColors: Color[] = GetEnumValues<Color>();

Just for reference, I am using Typescript version 3.9.4 but open to suggestions for newer versions.

Answer №1

It's quite simple to achieve. The only limitation is that you cannot use it with const enum. Typescript will generate an error if you attempt to do so, as it is not available at runtime.

function getEnumValues<T>(en: any): T[] { // perhaps it can be accomplished without using any, but I am unsure
   return Object.keys(en)
     .filter(k => !isFinite(Number(k))) // this filters out the reverse mappings: https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
     .map(k => en[k]);
}

For further reference, consider the following example: https://stackblitz.com/edit/typescript-z2swch

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

Typescript - A guide on updating the value of a key in a Map object

My Map is designed to store Lectures as keys and Arrays of Todos as values. lecturesWithTodos: Map<Lecture, Todos[]> = new Map<Lecture, Todos[]>(); Initially, I set the key in the Map without any value since I will add the Todos later. student ...

Having trouble accessing the theme in a styled component with @emotion/styled

https://i.stack.imgur.com/zHLON.png I've been using @emotion/react for theming and successfully injected the theme into it. I can access the theme using useTheme within components, but I'm facing some difficulties in accessing the theme within s ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string. Below is my attempted solution: var t = '1,234.04 km ...

typeorm migration:generate - Oops! Could not access the file

When attempting to create a Type ORM migration file using the typeorm migration:generate InitialSetup -d ormconfig.ts command, I encountered an error: Error: Unable to open file: "C:\_work\template-db\ormconfig.ts". Cannot use impo ...

Prevent click events on disabled tabs in PrimeNG tabMenu

I am encountering an issue with PrimeNG's p-tabMenu when it comes to disabled menu items. For example, suppose I have a tabMenu with 4 sub tabs labeled AAA, BBB, CCC, and DDD. This is how the menuItems are set up in the TypeScript component: //.... ...

What is the reason why the swiper feature is malfunctioning in my React-Vite-TS application?

I encountered an issue when trying to implement Swiper in my React-TS project. The error message reads as follows: SyntaxError: The requested module '/node_modules/.vite/deps/swiper.js?t=1708357087313&v=044557b7' does not provide an export na ...

Incorporate the {{ }} syntax to implement the Function

Can a function, such as toLocaleLowerCase(), be used inside {{ }}? If not, is there an alternative method for achieving this? <div *ngFor="let item of elements| keyvalue :originalOrder" class="row mt-3"> <label class=" ...

A step-by-step guide on retrieving the present date and time using TypeScript

Details This is my first time creating a VSCode extension using TypeScript, and I am having trouble displaying the current date/time in an information message. My Attempts I have searched through VSCode key bindings for any references to date/time, as w ...

Using an External JavaScript Library in TypeScript and Angular 4: A Comprehensive Guide

My current project involves implementing Google Login and Jquery in Typescript. I have ensured that the necessary files are included in the project: jquery.min and the import of Google using <script defer src="https://apis.google.com/js/platform.js"> ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

The attribute interface overload in Typescript is an important concept to

Consider a scenario where there are multiple payload options available: interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne ...

Looking for a more efficient approach to writing React styles for color?

Desire I am interested in customizing colors within Material UI components. Moreover, I aim to develop a React Component that allows for dynamic color switching through Props. Challenge The current approach using withStyles results in redundant and lengt ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

Why is it that in reactive forms of Angular, the parameter being passed in formControlName is passed as a string?

I am currently working on a reactive form in Angular. In order to synchronize the FormControl object from the TypeScript file with the form control in the HTML file, you need to utilize the formControlName directive. This is accomplished as shown below: f ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

Server-side props become inaccessible on the client side due to middleware usage

I'm attempting to implement a redirect on each page based on a specific condition using Next.js middleware. Strange enough, when the matcher in middleware.ts matches a page, all props retrieved from getServerSideProps for that page end up being undef ...

What is the process for assigning a predefined type that has already been declared in the @types/node package?

Is there a way to replace the any type with NetworkInterfaceInfo[] type in this code snippet? Unfortunately, I am unable to import @types/node because of an issue mentioned here: How to fix "@types/node/index.d.ts is not a module"? Here is the o ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

There was an error in the CSS syntax in the production environment due to a missed semicolon

Trying to execute the npm build command "webpack --mode=production --config ./config/webpack.config.prod.js" on our project results in an issue. The issue arises when I include the bootstrap file in my tsx file as shown below. import bs from "../../../../ ...