Converting Typescript enum values into an array

Can the values of an enum in TypeScript be accessed as an array?

For example:

enum MyEnum {
    FOO = 'foo',
    BAR = 'bar'
}

would become

['foo', 'bar']

Answer №1

A feasible approach is to utilize:

Object.values(MyEnum)

due to the fact that after compilation, an enum becomes a JS object:

var MyEnum;
(function (MyEnum) {
    MyEnum["FOO"] = "foo";
    MyEnum["BAR"] = "bar";
})(MyEnum || (MyEnum = {}));

Answer №2

If you're looking to ensure that your code is fully typed, one approach is to utilize the template literal operator in TypeScript to infer the list of values as a specific type:

enum MyEnum {
    FOO = 'foo',
    BAR = 'bar'
}

type MyEnumValue = `${MyEnum}`
// Result: type MyEnumValue = "foo" | "bar"

const valuesList: MyEnumValue[] = Object.values(MyEnum)
// Result: ["foo", "bar"]

For further information on dynamically obtaining the values of an enum, check out this reference article. (note: I am the author of the article)

Answer №3

If you're working with a string enum, the easiest method is to utilize the Object.values function

enum MyEnum {
    FOO = 'foo',
    BAR = 'bar'
}
console.log(Object.values(MyEnum));

Answer №4

Update:

In my opinion, @Fyodor's approach stands out as more efficient as it addresses string enums:

const enumValues = Object.values(MyEnum).filter(val => typeof val === 'string')

Answer №5

This code snippet demonstrates how to handle numeric enums and ensures type checking:

type EnumObject = {[key: string]: number | string};
type EnumObjectEnum<E extends EnumObject> = E extends {[key: string]: infer ET | string} ? ET : never;

function extractEnumValues<E extends EnumObject>(enumObject: E): EnumObjectEnum<E>[] {
  return Object.keys(enumObject)
    .filter(key => Number.isNaN(Number(key)))
    .map(key => enumObject[key] as EnumObjectEnum<E>);
}

For instance:

enum NumEnum {
    X,
    Y,
    Z,
}
// The resultant type will be inferred as NumEnum[]
let numEnumResults = extractEnumValues(NumEnum);

TypeScript Playground

Additional information can be found at: Exploring TypeScript Enum Values

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

What is the reason I am unable to both declare and define a char-pointer variable that points to a char-array?

What's the issue with initializing s2 in the code snippet below? #include <stdio.h> int main() { char *s1 = "foo"; char *s2 = {'f', 'o', 'o', '\0'}; printf("%c\n", s1[1]); printf("%c&b ...

How is it possible that function pointers can be invoked as both (*func_ptr)() and func_ptr(), but array pointers do not have this same flexibility?

Imagine we are given a function pointer func_ptr, which has the type void (*func_ptr)(). In this scenario, it is understood that we can call the function using this pointer in two ways: (*func_ptr)(); func_ptr(); However, what happens if we have a pointe ...

Adding Up Arrays and Converting to Integer in C

Currently, I am diving into the world of programming with C and find myself a bit perplexed by array manipulation. One of my assignments involves adding up two arrays containing only non-negative integers. For instance, given array 1 = {1,2.3} and array ...

There seems to be an issue with accessing the 'request' property of an undefined object

Currently, I am in the process of incorporating a base service into an Angular application. This service is designed to provide methods to other services for composing requests with default headers and options. However, I encounter an issue when attempting ...

Invoke the subscribe function within the encompassing parent function

In crafting a versatile method, I have devised the following code snippet: fetchArticle(loading: Loading): void { this.articleService.getArticleById(this.data.definition.id) .map((response: any) => response.json()) .subscribe((response: ...

Error in Angular caused by ChartJS: TypeError, inability to access property '_model' because it is null

I am currently working on a project that involves showcasing real-time data in a ChartJS graph. The data is retrieved from an external web server, and I have managed to store the data in 6 arrays (which are constantly changing) with each array containing 1 ...

Finding the index of an element in an array in TypeScript/JavaScript

UPDATE: Despite being labeled as a duplicate, this question showcases @ssube's clever and efficient solution. UPDATE2: A new method has been suggested by @Grungondola in the comments. I'm currently working with Typescript. This first code snip ...

Error message: TypeScript Partial Type does not match the expected type

After previously working without any issues, my code is now encountering a type error related to the logEntry: The following type error is occurring: Type '{ raw: string; timestamp: number; }' is not assignable to type 'Partial<ILogEntry ...

Utilizing a Python/Cython Numpy array by Sending Numpy Array to C Pointer

I have been facing an issue where I am attempting to pass a Cython-numpy array to a C struct. It works fine for arrays of 'small' size but crashes when the array size exceeds a certain limit. The strange thing is that the array size I am using is ...

Typescript is outputting the error message: "cannot be assigned to the type 'IntrinsicAttributes & { children?: ReactNode; }'"

While there has been extensive discussion on this topic, I am unable to get any other solutions from SO to work, or I am struggling to implement them. I am completely new to TypeScript, and here is what I have: import faker from "faker"; import React fro ...

Expanding unfamiliar categories

Currently, I am working with Gutenberg blocks in a headless manner. Each Gutenberg block is defined by the following structure: type Block = { name: string; className?: string; key?: string | number; clientId: string; innerBlocks: Block ...

What's the best way to extract a JSON string from a specific URL?

Looking to store JSON data in an array: arr[ ] array = {"http://www.ip-api.com/json"}; How can I print the JSON data itself instead of just showing "" as a string? ...

Using Angular: Accessing a specific object property within a collection for a Form input

Need assistance with handling a collection in an Angular component: collection: collectionAbs[]; export interface collectionAbs{ name: string; prop: string; secondProp: number; } Initialization: this.collection.forEach((item ,index) = ...

How to trigger a component programmatically in Angular 6

Whenever I hover over an <li> tag, I want to trigger a function that will execute a detailed component. findId(id:number){ console.log(id) } While this function is executing, it should send the id to the following component: export class ...

The ngOnChanges lifecycle hook does not trigger when the same value is updated repeatedly

Within my appComponent.ts file, I have a property called: this._userMessage Afterwards, I pass it to the childComponent like so: <child-component [p_sUserMessage]='_userMessage'></child-component> In the childComponent.ts file: @ ...

Angular is able to compare arrays and update them efficiently

Looking for a way to compare two arrays in Angular and update the status of objects in the first array if they are found in the second array. Any suggestions on how to manipulate the data? Here is an example of the arrays: arr1 = [ {id: 1, status: fals ...

Pause for a moment before commencing a fresh loop in the FOR loop in JavaScript

Behold, I present to you what I have: CODE In a moment of curiosity, I embarked on creating a script that rearranges numbers in an array in every conceivable way. The initial method I am working with is the "Selection mode", where the lowest value in th ...

Obtain a precise value from an array in Laravel

Working with Laravel and have an array that looks like this - [{"emp_id":1,"shift":"first","status":"Present","is_unpaid":0,"start":"2018-03-21 08:00:00","end":"2018-03-21 12:00:00"},{"emp_id":2,"shift":"first","status":"Present","is_unpaid":0,"sta ...

An effective way to cycle through a list to search for elements in a separate list

Is this code suitable for comparing around 200 guid strings in one list with 100 guid strings from another list to find matching indexes without impacting performance? The method signature I have defined is... -(NSArray*)getItemsWithGuids:(NSArray*)guids ...

How can I implement set/get/destroy methods in fastify-session to effectively save the session data in MongoDB?

I am working with TypeScript and trying to find a way to store sessions in mongoDB rather than in memory. After reading the documentation, I still couldn't figure it out (https://github.com/SerayaEryn/fastify-session). Can anyone guide me on how to ac ...