typescript - 不能在 Typescript Map 中使用数字作为键?

标签 typescript dictionary

在类里面:

private stuff: Map<number, string> = new Map();

...

this.stuff[aNumber] = "hello";

给出这个错误:

Element implicitly has an any type because expression of type number can't be used to index type Map<number, string>.

No index signature with a parameter of type number was found on type Map<number, string>

这对我来说毫无意义。为什么不 Map<number, string>使用 number 类型的参数声明索引签名?

最佳答案

这是因为 Map 没有使用索引器——它使用的是 get/set 方法。

let foo: Map<number, string> = new Map();
foo.set(2, "something");
let some = foo.get(2);

你可以做的是使用 number: string 自定义 map 对象

let bar: { [key: number]: string } = {};
bar[1] = "some";
bar["sl"] = "some" // error

请参阅playground .

关于typescript - 不能在 Typescript Map 中使用数字作为键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58266563/

相关文章:

node.js - 不使用 Promises 的动态 TypeScript 导入

typescript - 将一组 promise 转换为一个 promise ,该 promise 可能是包含的类型之一 : [P<string>, P<number>] -> Promise<string |号码>

c# - 自定义类作为 C# 中字典的键不起作用

r - 为什么 mapply 不能按预期使用转换?

Angular 6 文件上传预览仅在第二次上传后有效

typescript - 如何使用 TypeScript 导入外部文件?

typescript 同一类型的多个泛型

python - 从 NLTK 的 Penn Treebank 语料库样本创建字典?

google-app-engine - 如何从数据存储模型创建嵌套字典?

Python:根据替换字典/替换映射替换字符串列表中的匹配项