Utilizing TypeScript 3.1: Easier Array Indexing with Enums in Strict Mode

Enabling TypeScript "strict" mode with "noImplicitAny" causes this code to fail compilation.

I am looking for guidance on how to properly declare and use Arrays indexed by Enum values.

namespace CommandLineParser {
    enum States { sNoWhere, sSwitchValue }

    abstract class State {        
    }

    class NoWhereState extends State {

    }

    class SwitchValueState extends State {

    }

    export class GetOption {
        state: State;
        states: Array<State>[States];

        constructor() {
            this.states = new Array(2);
            this.states[States.sNoWhere] = new NoWhereState();
            this.states[States.sSwitchValue] = new SwitchValueState();
            this.state = this.states[States.sNoWhere];
        }
    }
}

let go = new CommandLineParser.GetOption();

The errors encountered are :

error TS7017: Element implicitly has an 'any' type because type 'State' has no index signature.

          this.states[States.sNoWhere] = new NoWhereState(this);
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

error TS7017: Element implicitly has an 'any' type because type 'State' has no index signature.

          this.states[States.sSwitchValue] = new SwitchValueState(this);
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

error TS7017: Element implicitly has an 'any' type because type 'State' has no index signature.

          this.state = this.states[States.sNoWhere];
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Answer №1

Although this may seem a bit outdated and not directly addressing the question, I personally find it more intuitive to use objects instead of arrays in situations like yours. Take into consideration the following approach:

enum MyIndexingEnum { stateOne, stateTwo }
const someIndexedObject {
  [MyIndexingEnum.stateOne]: { /* data */ }
  [MyIndexingEnum.stateTwo]: { /* data */ }
}

/* Retrieving data */
someIndexedObject[MyIndexingEnum.stateOne]

Answer №2

The issue lies in the data type of states. Initially, you define an array of type State, but later on, you utilize a type query which results in just State. The statement this.states = new Array(2); is successful because the State class does not have any members, allowing the array to technically fulfill the class signature.

To rectify this problem, consider the following solution:

export class GetOption {
    state: State;
    states: Array<State>;

    constructor() {
        this.states = new Array(2);
        this.states[States.sNoWhere] = new NoWhereState();
        this.states[States.sSwitchValue] = new SwitchValueState();
        this.state = this.states[States.sNoWhere];
    }
}

It should be noted that with this approach, you can access the array using any number, not just limited to enum types, which may not align with your requirements. Alternatively, if you do not require the array methods, utilizing a simple object might be more suitable, albeit requiring initialization at once (or you can use a type assertion like this.states = {} as any):

export class GetOption {
    state: State;
    states: Record<States, State>;

    constructor() {
        this.states = {
            [States.sNoWhere]: new NoWhereState(),
            [States.sSwitchValue] : new SwitchValueState()
        }
        this.state = this.states[States.sNoWhere];
        this.state = this.states[10]; //error
    }
}

Another viable option would be to use a tuple type since the enum constants correspond to numbers, and it offers access to array methods if needed:

export class GetOption {
    state: State;
    states: [State, State];

    constructor() {
        this.states = [new NoWhereState, new SwitchValueState]
        this.state = this.states[States.sNoWhere];
        this.state = this.states[10]; //error
    }
}

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

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Is it possible to set the state of my datepicker to a previous value only if the new one is determined to be invalid?

I am currently facing an issue with a library I'm utilizing, which has the potential to generate incorrect values that may cause my page to crash. To prevent this, I want to ensure that only valid values (the result of useDateRangePickerState) are app ...

Error in Typescript for a function that accepts several types of lists - property does not exist on the interface

In my project, I have defined three interfaces: a base interface and two others that extend the base one with children as properties. One of the interfaces includes 'valueType' while the other includes 'returnType'. Here is how they are ...

Issue with Value Update in Angular 7 Reactive Forms

I am encountering an issue where the data in my formgroup does not update upon submission. The formgroup successfully retrieves values from an API, but when attempting to update and return the value, it remains unchanged. I am unsure of what mistake I may ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

Error with Angular 2 observables in TypeScript

When a user types a search string into an input field, I want to implement a debounce feature that waits for at least 300 milliseconds before making a request to the _heroService using HTTP. Only modified search values should be sent to the service (distin ...

The error message "Property not found on type 'Product | Customer' in React Typescript" is indicating that the specified property does not exist on the

I am currently working on a React app using TypeScript where I need to manage data for Customers and Products. To enhance this functionality, I plan to create a form component that can be used for updating either a Customer or a Product. The idea is to pr ...

Utilize TypeScript function types in React for enhanced functionality

I have made the decision to refactor a project that was originally created with vanilla JavaScript and now I want to transition it to TypeScript. One issue I am facing is how to pass a function as a type on an interface. Although I referred to the TypeScr ...

Invoke a function in Angular when the value of a textarea is altered using JavaScript

Currently, I am working with angular and need to trigger my function codeInputChanged() each time the content of a textarea is modified either manually or programmatically using JavaScript. This is how my HTML for the textarea appears: <textarea class ...

Effortlessly adding custom classes in Angular 2 with a breeze

Imagine having a growing Angular2 typescript solution with numerous small classes and objects. Following the best practice, each class is placed in its own file. However, manipulating these objects leads to long lists of imports like: import {Object1} f ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

Can you explain the rule known as the "next-line" in TypeScript?

No code examples are available for the specific scenario described below: "next-line": [ true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace" ], ...

The function 'appendChild' is not recognized on the type 'unknown'.ts(2339)

I'm encountering an issue while trying to integrate the Utterances component into my articles. Upon attempting to build the site, I receive the following error message: "Property 'appendChild' does not exist on type 'unknown' ...

The error message "Property '...' is not found on the type 'ServerContextJSONValue'" pops up whenever I try to utilize the useContext() function

After creating a Provider and defining the type, I encountered a TypeScript error when using it with useContext(): "Property '...' does not exist on type 'ServerContextJSONValue'. I'm not sure what I am missing. Can anyone help me ...

Testing Slack's Web API with Jest for mock purposes

Currently, I am working with two files. One file is where I set up a slack web API client to post a message and test it with a mocked value: main.ts: import { WebClient } from '@slack/web-api'; const slack = new WebClient(process.env.SLACK_API_K ...

Encountering a new challenge in Angular: The error "InvalidPipeArgument: '' for pipe 'AsyncPipe'

Whenever I try to fetch data from the server, these errors keep popping up. This code was written by someone else and I would like to improve upon it. Could anyone suggest the best approach to handle this situation? Are there any coding patterns that sho ...

Incorporating an alternate object array to update an array of objects: A

There are two object arrays, the main array and the temp array. The goal is to compare the main array with the temp array and update the values in the main array based on matching IDs. In this example, IDs 2 and 3 match in both arrays. Therefore, the valu ...

What's causing the subscription feature to malfunction in a fresh browser tab?

I am facing an issue with camera entries on an angular website. Whenever I click on an entry, a new window opens to display the camera livestream. However, I am having trouble with the subscribe functionality. Important note: Once the window is open, subs ...

Discover a Simple Trick to Enhance tsc Output: Unveil the Art of

When I work on a TypeScript project, I typically use the watch mode of the compiler: tsc --watch However, one issue I face is that it's challenging to identify errors in the output since they are displayed as plain text: Sometimes I don't even ...

Issues with user-generated input not properly functioning within a react form hook

After following the example provided here, I created a custom input component: Input.tsx import React from "react"; export default function Input({label, name, onChange, onBlur, ref}:any) { return ( <> <label htmlF ...