如何使用用户定义的键声明关联数组?

How to declare an associative array with user-defined key?

我的尝试:

class Key {
    foo: string = "";
}

var dict = new Map<Key, number>();
dict[new Key()] = 1; // <-- error here

我遇到一个错误:

Type 'Key' cannot be used as an index type.

我也考虑过使用普通的 JS“对象”(它具有关联数组的功能),但它们只能由字符串索引。

我也试过了Record:

class Key {
    foo: string = "";
}

var dict : Record<Key, number> = {}; // <-- error here
dict[new Key()] = 1;

得到:

Type 'Key' does not satisfy the constraint 'string | number | symbol'. Type 'Key' is not assignable to type 'symbol'.

我也试过索引签名:

class Key {
    foo: string = "";
}

interface MyDict {
    [index: Key]: number; // <-- error here
}

var dict = new MyDict();
dict[new Key()] = 1;

得到:

An index signature parameter type must be either 'string' or 'number'.

那么,如何使用用户定义的键声明关联数组?

使用Map,你不使用theMap[key] = value(那是设置对象属性),你使用set方法:

dict.set(new Key(), 1);

同样,要从 Map 中获取值,您可以使用 get 方法:

value = dict.get(someKey);