Typescript 如何使用用户定义的键声明关联数组?
我的尝试:Typescript 如何使用用户定义的键声明关联数组?,typescript,associative-array,Typescript,Associative Array,我的尝试: class Key { foo: string = ""; } var dict = new Map<Key, number>(); dict[new Key()] = 1; // <-- error here 得到: 类型“Key”不满足约束“string | number | symbol”。 类型“Key”不可分配给类型“symbol” 我还尝试了索引签名: class Key { foo: string = "
class Key {
foo: string = "";
}
var dict = new Map<Key, number>();
dict[new Key()] = 1; // <-- error here
得到:
类型“Key”不满足约束“string | number | symbol”。
类型“Key”不可分配给类型“symbol”
我还尝试了索引签名:
class Key {
foo: string = "";
}
interface MyDict {
[index: Key]: number; // <-- error here
}
var dict = new MyDict();
dict[new Key()] = 1;
类密钥{
foo:string=“”;
}
接口MyDict{
[index:Key]:number;//对于Map
,您不使用theMap[Key]=value
(用于设置对象属性),而是使用以下方法:
类似地,要从映射
中获取值,请使用以下方法:
使用Map
,您不需要使用Map[key]=value
(用于设置对象属性),您可以使用以下方法:
类似地,要从映射
中获取值,请使用以下方法:
class Key {
foo: string = "";
}
interface MyDict {
[index: Key]: number; // <-- error here
}
var dict = new MyDict();
dict[new Key()] = 1;
dict.set(new Key(), 1);
value = dict.get(someKey);