如何在 Typescript 中为 Map 的类型别名定义索引签名?

How to define index signature for a type alias of a Map in Typescript?

如果我像这样为 Map 定义类型:

type MyCustomMap = Map<string, number>;

如何添加索引签名以便在创建后设置键值?我已经能够使用定义不同属性的类型来做这样的事情,例如:

type MyCustomObj = {
    [key: string]: any;
    something: string;
}

但是在上述情况下我找不到方法。

我想你正在寻找这样的东西:

type MyCustomObj<Key extends string | number, Value, Rest = {}> =
    Key extends string ? { [key: string]: Value } & Rest: { [key: number]: Value } & Rest;

你可以这样使用它:

type Obj = MyCustomObj<string, number>;
type CustomObj = MyCustomObj<string, number, { key: boolean }>;

Playground