Home > Enterprise >  How to deal with index signature for a simple object
How to deal with index signature for a simple object

Time:10-15

I'm trying to convert the returned number status to a string in the UI like so:

{statuses[job.status]}

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

But getting this message:

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

I've tried adding an interface but still getting the same issue

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

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

I've searched for ways around this, but can't seem to get it working in my instance.

CodePudding user response:

Just need to add Index Signature to your interface

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

Demo

CodePudding user response:

Just do this:

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

Refer: Record<Keys, Type>


You can also use keyof like this:

{statuses[job.status as keyof statuses]}

If you just have 1, 2, 3, 4 as keys, then it is better to just type your job.status as 1 | 2 | 3 | 4 (same as keyof statuses). Record<number, string> will accept all numbers as key, which may result in weaker type checking. If you are not getting job from some external source, you can try using enums too.

  • Related