Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何使用用户定义的键声明关联数组?_Typescript_Associative Array - Fatal编程技术网

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);