Home > Mobile >  How to write a key pair generic "type" typescirpt
How to write a key pair generic "type" typescirpt

Time:10-26

I'm waiting to write a key value pair type for flat objects. But when I user this type in a global s type file I get this error.

// 1. this is what I'm currently using. 
type KEY_VALUES = { [k: string | number]: any; };

// 2. I thought it should be something like this.
type KEY_VALUES = { [k: string | number]: [value: any]; };

1. Error: An index signature parameter type cannot be a union type. Consider using a mapped object type instead.

2. Error: An index signature parameter type cannot be a union type. Consider using a mapped object type instead.

What is the best way to achieve this?

CodePudding user response:

Consider using a mapped object type instead.

Have you tried that?

type KEY_VALUES = {
    [k in string | number]: any;
};

CodePudding user response:

Apart from @SeanAH solution, you can use string pattern index signatures:


type KEY_VALUES = { [k: string | `${number}`]: [value: any]; };

  • Related