gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 06:23:32 25 4
gpt4 key购买 nike

在类里面:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com