Tips for managing an index signature in a basic object

I'm attempting to transform the received numerical status into a corresponding string for the user interface like this:

{statuses[job.status]}

const statuses = {
  1: "Processing",
  2: "Done",
  3: "Aborted",
  4: "Queued",
}

However, I am encountering the following error:

No index signature with a parameter of type 'number' was found on type '{ 1: string; 2: string; 3: string; 4: string; }'

I have attempted to address this by introducing an interface, but the issue persists

interface IStatus {
  1: string;
  2: string;
  3: string;
  4: string;
}

const statuses = {
  1: "Processing",
  2: "Done",
  3: "Aborted",
  4: "Queued",
} as IStatus;

I have explored various solutions to this problem, but have been unsuccessful in resolving it in my particular case.

Answer №1

To achieve this, follow these steps:

const statuses: Record<number, string> = {
  1: "Processing",
  2: "Done",
  3: "Aborted",
  4: "Queued",
  // ...
}

For more information, see: Record<Keys, Type>


Alternatively, you can utilize keyof in this manner:

{statuses[job.status as keyof statuses]}

If your keys are only 1, 2, 3, 4, it's recommended to type job.status as 1 | 2 | 3 | 4 (similar to keyof statuses). Using Record<number, string> may allow any number as a key, potentially weakening type validation. If job is not sourced externally, consider exploring enums as well.

Answer №2

To enhance your interface, simply incorporate an Index Signature like so:

interface IStatus {
    [key: number]: string,
    1: string;
    2: string;
    3: string;
    4: string;
}

For a visual demonstration, check out this demo

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

Functions outside of the render method cannot access the props or state using this.props or this.state

Just starting out with react. I've encountered an issue where a prop used in a function outside the render is coming up as undefined, and trying to use it to set a state value isn't working either. I've researched this problem and found va ...

Is it correct to implement an interface with a constructor in TypeScript using this method?

I am completely new to TypeScript (and JavaScript for the most part). I recently came across the article discussing the differences between the static and instance sides of classes in the TypeScript handbook. It suggested separating the constructor into an ...

Implementing the handling of multiple button events in a ListView through onclick function

Currently, I have a listview with three buttons that need to trigger the same method checkInstall on multiple button clicks. However, I am unsure of how to achieve this. Below is the relevant code snippet: html file: <ListView [items]="allAppsList" c ...

Utilizing electron and Systemjs to import node modules

Is it feasible for systemjs to utilize require("remote").require("nodemodule") when the module cannot be located in its registry? A similar mechanism seems to be functioning when utilizing electron with typescript and commonjs modules... Has anyone succe ...

Loop through an array of strings

When I receive the data as a string[] https://i.sstatic.net/ttyag.png However, when I attempt to loop over it subUrl(arr) { for(let i of arr) { console.log(i); } } No output is being logged. What could be causing this issue? ...

What could be causing Next.js to re-render the entire page unnecessarily?

As a newcomer to Next.js, I am trying to develop an app where the header/navbar remains fixed at all times. Essentially, when the user navigates to different pages, only the main content should update without refreshing the navbar. Below is the code I have ...

NextJs Link component does not refresh scripts

While using the <Link> tag in NextJs for page navigation, I encountered an issue where my scripts do not rerun after switching pages. The scripts only run on the initial page load or when I manually reload the page. This behavior is different when us ...

Sending Information to Routes - Error: No Routes Found to Match

I recently tried implementing a solution from an article () to pass an ID between modules in order to use it as a search filter. However, I encountered the "cannot match any routes" error and have been struggling for some time since I'm new to Angular ...

Encountering issues with accessing properties of undefined while chaining methods

When comparing lists using an extension method that calls a comparer, I encountered an error. Here is the code snippet: type HasDiff<T> = (object: T, row: any) => boolean; export const isListEqualToRows = <T>(objects: T[], rows: any[], has ...

Unable to modify data with ionic and firebase in child node format

I am encountering an issue when updating data with Ionic Firebase using the following code. Instead of rewriting the previous data, it simply creates new data entries. Here is the code snippet: updateLaporan() { this.id =this.fire.auth.cur ...

Accessing JSON data from a database using Angular

Wondering if there is a way to effectively access and manipulate JSON data stored in a database using Angular. While researching online, I keep coming across methods for reading JSON files from the Asset Folder, which does not align with what I need. What ...

Creating a String-only pattern Validator: A step-by-step guide

Below is the code I've written: ***<input type="text" placeholder="First Name" name="firstName1" [(ngModel)]="firstName" #firstName1="ngModel" required pattern="^[a-z0-9_-]{8,15}$" >*** ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

The category 'Moment' cannot be assigned to the category 'Date'. The characteristic 'toDateString' is not present in the category 'Moment'

I recently integrated moment into my Angular2 application, and encountered an issue when attempting to assign the date of this week's Saturday to a variable of type date, case "weekend": this.fromDate = moment().startOf('week ...

Tips for refining TypeScript discriminated unions by using discriminators that are only partially known?

Currently in the process of developing a React hook to abstract state for different features sharing common function arguments, while also having specific feature-related arguments that should be required or disallowed based on the enabled features. The ho ...

Utilize Azure Functions: Employ the Apollo Azure handler within an asynchronous function

Looking to incorporate some checks before executing the apollo handler function, I attempted to wrap it in an async function. However, when exporting the function as async, it consistently returns an empty response. functions.json { "bindings" ...

States are consistently maintained in React and do not impact the rendering process

I am keeping track of a state value by declaring it like this: const [count, setCount] = useState(0); To increment the count: const incrementCount = () => { setCount(count + 1); } I use this function in a loop to iterate through an array, exec ...

Clicked but nothing happened - what's wrong with the function?

For my project, I have incorporated tabs from Angular Material. You can find more information about these tabs here. Below is the code snippet I am using: <mat-tab-group animationDuration="0ms" > <mat-tab></mat-tab> < ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

Integrate service once the constructor has completed execution

I created a service to connect with the Spotify API. When initializing this service in the constructor, it needs to retrieve the access token by subscribing to an Observable. However, there's an issue: The service is injected into my main component ...