Traversing the enum's keys poses a challenge in terms of typing

Imagine you need to display all values of an enum

enum AnEnum {
    a = 'a',
    b = 'b'
}

const keys = Object.keys(AnEnum);

keys.forEach(key => {  
     console.log(AnEnum[key]);
});

This results in the following error message:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof AnEnum'. No index signature with a parameter of type 'string' was found on type 'typeof AnEnum'

DEMO

The only solution I could come up with is adding any

(AnEnum as any)[key]

However, I believe there should be a better workaround. Any recommendations?

Answer β„–1

Exploring the functionality of Object.keys() method in TypeScript can provide insights into its typing within the standard library, as seen below:

interface ObjectConstructor {
  keys(o: object): string[];
}

The return type specified is string[]. This signifies that Object.keys(obj) yields a value of type Array<string>, rather than Array<keyof typeof obj>, where each key represents a union based on the known keys of an object. The compiler may not be able to ascertain if an object only contains the exact keys it knows about.

If attempting to access an object using a solely known string key, confirmation of having a string index signature for the object is necessary. Failure results in the compiler generating warnings and assuming the any type.


In scenarios where you are certain of an object's contained keys (e.g., a string enum without reverse mappings), employing a type assertion informs the compiler accordingly:

const keys = Object.keys(AnEnum) as Array<keyof typeof AnEnum>;

Subsequently, iterating through the loop works as intended:

keys.forEach(key => {
    console.log(AnEnum[key]); // outputs correctly
});

Note that utilizing

Object.keys(obj) as Array<keyof typeof obj>
has limitations too. If additional unknown keys exist within
obj</code}, especially with values differing from the known ones, runtime errors may occur despite successful compilation:</p>
<pre><code>interface Foo {
    a: string,
    b: string
}
const f = { a: "hello", b: "goodbye", c: 123 };
const foo: Foo = f; 

(Object.keys(foo) as Array<keyof Foo>).forEach(k => console.log(foo[k].toUpperCase()));
// Prints:
// HELLO
// GOODBYE
// πŸ’₯ RUNTIME ERROR! foo[k].toUpperCase is not a function

It is advised to exercise caution when implementing such practices!

Check out this Playground link for interactive code snippets

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

Accessing the currently operating WS server instance with NodeJS

After successfully setting up a basic REST API using NodeJS, ExpressJS, and routing-controllers, I also managed to configure a WebSocket server alongside the REST API by implementing WS. const app = express(); app.use(bodyParser.json({limit: "50mb"})); a ...

Submit user-specific form data in Angular 5 based on user selection

Utilizing a common reactive form to handle various types of user data, such as teachers, students, guards, etc. The form is selected from a dropdown list. The goal is to send specific data objects based on the selected user type. A model named "User" has ...

Obtain one option from the two types included in a TypeScript union type

I am working with a union type that consists of two interfaces, IUserInfosLogin and IUserInfosRegister. The TUserInfos type is defined as the union of these two interfaces. export interface IUserInfosLogin { usernameOrEmail: string; password: string; } ...

In React and TypeScript, when I pass a state as a prop, the data fails to render

Here is the useState function for managing the Data Interestingly, removing this state from the code doesn't affect rendering at all. const [cart, setCart] = useState([] as Product[]); This piece of code handles Mapping and Rendering the Data <Sin ...

Is the graphql codegen accurately generating the types?

I'm in the process of developing a basic Next.js application with TypeScript by integrating Strapi as a headless CMS. The main goal is to use Strapi and GraphQL, along with TypeScript, to display content on the Next.js app. Within Strapi, there is a ...

Transfer the HTTP functionality to a separate service using Angular2 and TypeScript

Currently diving into learning Angular2 and TypeScript after years of using Angular 1.*. I have a top level component that has a property derived from a custom type created in another class. When ngOnInit() is triggered, it makes an HTTP call to a mock RES ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

How can I configure Material-UI's textfield to return a numerical value instead of a string when the type is set to "number"?

Utilizing Material-UI's TextField alongside react-hook-form to monitor inputs has raised an issue for me. I have observed that regardless of the input type, it always returns a string. This creates conflicts with the data types I am using in my codeba ...

The function signature '() => Element' is incompatible with the type 'string'

Greetings! I have a standard function that returns a span with a prop (if I'm not mistaken). In my TS code, I am encountering this error: Error image Below is the code from the file named qCard.tsx: import { QuestionAnswerTwoTone } from "@material- ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

"Type 'Unknown' cannot be assigned to the specified type: Typescript Error encountered while using

I encountered an error message in my Redux Observable setup. Any advice on how to resolve this issue? The error states: 'Argument of type 'OperatorFunction<ITodo[], Action<{ params: { url: string; }; } & { result: { todos: ITodo[]; }; ...

"Elaborate" Typescript Conditional Generic Types

Scenario I am currently working on implementing strong typing for the onChange function of a UI library's Select component. To provide some context, the existing type definition for their onChange is as follows: onChange?: (...args: any[]) => v ...

Exploring the power of RxJs through chaining observers

In my Angular application, I am utilizing Observables to set up a WebSocket service. Currently, I have the following implementation: readwrite(commands: command[]) : Observable<response[]>{ const observable = new Observable((observer)=>{ ...

The function `Object.entries().map()` in TypeScript does not retain the original data types. What changes can I make to my interface to ensure it works correctly, or is there a workaround

Working with this interface: export interface NPMPackage { name: string; description: string; 'dist-tags': { [tag: string]: string; }; versions: { [version: string]: { name: string; version: string; dependencie ...

Nuxt3 - TS2339: The 'replaceAll' property is not found on the 'string | string[]' type in Nuxt3

Hey there! I've been experimenting with the replaceAll() method within my Nuxt3 project and encountered a strange error. Folder Structure ───pages β”‚ └───Work β”‚ β”‚ index.vue β”‚ β”‚ [Work].vue Template <templat ...

What is the process for extracting the elements of an array fetched from a service in Angular 2?

Currently, I am learning Angular 2 + PrimeNG and going through a quick start project available at the following link: https://github.com/primefaces/primeng-quickstart The project is a CRUD application and it functions flawlessly. The data is neatly displa ...

Using Typescript to test with Karma, we can inject a service for our

I'm currently experiencing a problem with running tests in my application. I recently transitioned to using TypeScript and am still in the learning process. The specific error I'm encountering is: Error: [$injector:unpr] Unknown provider: movie ...

Customizing the Switch component individually for each item fetched from an API in React Native

I'm struggling with setting the switch button individually for each item in my API. Despite trying multiple solutions, none of them seem to work for me. const results = [ { Id: "IySO9wUrt8", Name: & ...

Encountering the error message "Expected undefined to be truthy" while testing the creation of a Component

Recently, I've been tasked with enhancing my skill set by writing Jasmine/Karma tests for an Angular 9 application. After completing an online tutorial and doing some research via Google, I began working on my initial test cases independently. However ...

Is it possible for an object to be undefined in NextJS Typescript even after using a guard

Hey there, I could really use some help with a React component I'm working on. This is one of my initial projects and I've encountered an issue involving fetching async data. Below is the current state of my solution: import { Component } from &q ...