【问题标题】:How to define index signature for a type alias of a Map in Typescript?如何在 Typescript 中为 Map 的类型别名定义索引签名?
【发布时间】:2019-02-09 17:46:38
【问题描述】:
如果我为 Map 定义了这样的类型:
type MyCustomMap = Map<string, number>;
如何添加索引签名,以便在创建后设置键值?我已经能够使用定义不同属性的类型来做这样的事情,例如:
type MyCustomObj = {
[key: string]: any;
something: string;
}
但在上述情况下我找不到方法。
【问题讨论】:
标签:
javascript
typescript
typescript2.0
typing
【解决方案1】:
我想你正在寻找这样的东西:
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