gpt4 book ai didi

typescript - 为什么 typescript 允许我使用数字作为字符串映射的索引值?

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:49 25 4
gpt4 key购买 nike

我希望 typescript 将此报告为错误:

const map: { [key: string]: string } = {};
const value = map[1]; // 1 is not a string...

为什么 typescript 在这里没有提示?

最佳答案

在 javascript 中,对象的键始终是字符串,如果您传递数字,它将自动转换为字符串。

Let obj = {};
obj[3] = ‘something’;
console.log(Object.keys(obj));
// [‘3’]

如果您使用 map ,您可以将键值严格键入为

let m = new Map<string, any>();
m.set(3, "1st three");
m.set("3", "2nd three");

关于typescript - 为什么 typescript 允许我使用数字作为字符串映射的索引值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51526788/

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