网站搜索

为什么 TypeScript 允许我将数字作为字符串映射的索引值?


我希望 TypeScript 会将此报告为错误:

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

为什么 TypeScript 在这里没有报错?

答案#1

在 JavaScript 中,对象的键总是一个字符串,如果你传入一个数字,它会自动被转换为字符串。

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

如果你使用地图,你可以严格类型化键值为

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