Converting Enum into an array in TypeScript to return the keys of the Enum

After defining the following enum:

export enum Types {
    Type1 = 1,
    Type2 = 2,
    ...
}

We can create an array based on this enum with the function below:

export function EnumKeys<T>(obj: object): string[] {
    return Object.keys(obj)
        .filter(value => isNaN(Number(value)) === false)
        .map(key => obj[key]);
}

The EnumKeys function currently returns a string[], but I require it to return [keyof typeof T]

Answer №1

Object.keys intentionally returns a string[] (refer to main question here). To convert Object.keys(obj) into Array<keyof T>, you will need to utilize a type (assuming the T type parameter for the type of obj).

 enum Types {
    Type1 = 1,
    Type2 = 2,

}

function EnumKeys<T>(obj: T) {
    return (Object.keys(obj) as Array<keyof T>)
        .filter(value => isNaN(Number(value)) !== false); // only consider non-number keys.
}

let o = EnumKeys(Types) 
console.log(o)

Play around with it here

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

Exploring Improved Methods for Implementing Nested Subscriptions in Typescript

In my Typescript code for Angular 11, I am working with two observables. The first one, getSelfPurchases(), returns data objects containing information like id, user_id, script_id, and pp_id. On the other hand, the second observable, getScriptDetails(32), ...

Hold off on utilizing information from a single observable until a later time

In my Angular component, I am working with the following code: @Component({...}) export class ComponentOne implements OnDestroy, OnChanges { readonly myBehaviourSub = new BehaviorSubject<Observable<MY_CUSTOM_INTERFACE>>(NEVER); constructo ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

What is the best way to emphasize specific months and years in an Angular Material datepicker?

I have an array of days, which can be from any year. I am attempting to customize the Angular Material datepicker to highlight specific months and years in the selection views based on the array of days. .html <input [matDatepicker]="picker" ...

io-ts: Defining mandatory and optional keys within an object using a literal union

I am currently in the process of defining a new codec using io-ts. Once completed, I want the structure to resemble the following: type General = unknown; type SupportedEnv = 'required' | 'optional' type Supported = { required: Gene ...

Something went wrong: Unable to access the properties of an undefined variable named 'gametitle'

I am able to see the variables on the html-page, but I encountered an error specifically with the value of the gametitle ERROR TypeError: Cannot read properties of undefined (reading 'gametitle') Below is the content of the ts-file: import { ...

What is the best way to confirm the return type of a React.Component instance?

When working with TypeScript, there is a React Component called Cell: class Cell extends Component<void, void> { ... } Using it like this: <Cell /> The return type being received is JSX.Element. However, I want to make sure that the return ...

Derive a data type from a parameter passed to a function defined within an interface

I am working with a function defined in an interface as shown below: interface UseAutocompleteReturnValue { ... getRootProps: (externalProps?: any) => React.HTMLAttributes<HTMLDivElement>; } Within my interface, I aim to create a prop named rootP ...

Can you please provide instructions on how to obtain the TypeScript definitions file for a specific version of Jquery, such as 3.2.1

As I navigate my way through TypeScript, I find myself in need of accessing type definitions for a jQuery project in Visual Studio. The project currently utilizes jquery version 3.2.1, and I'm on the lookout for TypeScript type definitions for it. Af ...

Is it impossible to use type as a generic in TypeScript?

Struggling with TypeScript in React and encountered an issue. I decided to use a generic to build an abstracted class related to Axios. However, I ran into an ESLint error when using any as the type parameter for my generic. ESLint: Unexpected any. Specif ...

Common problems encountered post Typescript compilation

I encountered the same problem. Below is my tsconfig settings: "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "newLine": "LF", &q ...

Extracting data from an array using Angular

Currently, I am developing an Angular application that involves handling an array structured like the one below. [ { Code: "123", Details:[ { Id: "1", Name: "Gary" }, { ...

What is the best way to delay an observable from triggering the next event?

In my Angular project, I am implementing RxJs with two subjects. s1.next() s1.subscribe(() => { // perform some operation and then trigger the event for s2 s2.next() }); s2.subscribe(() => { // perform some operat ...

Using TypeScript - Implementing Reduce function with a return type containing optional fields

I am facing challenges in satisfying the TypeScript compiler with my code. I define a type that includes only optional fields, for example: interface UserData { email?: string; phone?: string; //... } and I have a reduction function that transforms ...

What is the reason behind Typescript raising an error when attempting to compare two boolean variables with different values (true and false)?

In the screenshot below, you can see that we are encountering a peculiar error when attempting to compare a boolean variable with true. This condition will always return 'false' since the types 'false' and 'true' have no over ...

Preventing specific directories from being imported in a Typescript project

I am intrigued by the idea of restricting files within a specific scope from importing files from another scope. Let's consider this example: Imagine we have the following project structure: project/ ├── node_modules/ ├── test/ ├── ...

Dynamic Angular Menu

Is there a cleaner, more dynamic way to implement a mat menu with individual click values and disable properties for each button? I want to avoid repeating code like in the example below. Looking for a more dynamic solution. #code <mat-menu #createDeal ...

Vercel encountered issues with "validating code quality and type correctness" during deployment but was successful when performed locally

Running "next build" locally and "vercel build" both work smoothly. However, once deployed to vercel, the "Linting and checking validity of types" fails during the build process. It seems like TypeScript is stricter when building on vercel even with the sa ...

Interpret information in Angular 2 using Typescript

Just starting with Angular (IONIC) and need help. How can I extract the userId or id from this code? his.response = data. //Looking for guidance on accessing Json keys Response : { "userId": 1, "id": 1, "title": "sunt aut facere repellat providen ...

Cannot see the template on the Angular Typescript component

After encountering and resolving this issue: AngularJS directive not displaying the template I decided to experiment with an Angular component and TypeScript, but unfortunately, I can't seem to make it work. The component refuses to display. This is ...