如何编写密钥对通用 "type" 打字稿

How to write a key pair generic "type" typescirpt

我正在等待为平面对象编写键值对类型。 但是当我在全局 s 类型文件中使用这种类型时,我得到了这个错误。

// 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.

实现此目标的最佳方法是什么?

Consider using a mapped object type instead.

你试过了吗?

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

除了@SeanAH 解决方案,您还可以使用 string pattern index signatures:


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