如何在TypeScript中创建通用Map接口

How to create generic Map interface in TypeScript

我想在TypeScript中创建一个Map接口,但是我似乎无法弄清楚如何限制属性访问器来使编译器满意

所需的接口

1
2
3
export interface IMap<I extends string | number, T> {
  [property: I]: T;
}

错误:

An index signature type must be 'string' or 'number'


您可以定义字符串和数字索引签名。

从规格:

An object type can contain at most one string index signature and one numeric index signature.

因此,您可以执行以下操作:

1
2
3
4
interface IMap< T > {
    [index: string]: T;
    [index: number]: T;
}

那是你的追求吗?

另外,当您仅定义字符串索引签名时:

Specifically, in a type with a string index signature of type T, all properties and numeric index signatures must have types that are assignable to T.

所以:

1
2
3
4
5
6
7
8
9
class Foo {
    [index: string]: number;
}

let f = new Foo();

f[1] = 1; //OK

f[6] ="hi"; //ERROR: Type 'string' is not assignable to type 'number'