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']
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']
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 = {}));
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)
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));
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')
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);
Additional information can be found at: Exploring TypeScript Enum Values
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 ...
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 ...
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 ...
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 ...
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: ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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? ...
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) = ...
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 ...
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: @ ...
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 ...
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 ...
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 ...
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 ...
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 ...