TypeScript 模拟 字典 Dictionary
文章目录
Map是在ES6出现的。所以当TypeScript的target是es5,并且没有在lib中添加ES2015,TypeScript中不能直接用Map。这种情况我们可以使用索引类型模拟。
// key 为 string,value 为 number;
const dic: { [key: string]: number; } = {
key1: 1,
};
// 添加key,value;
dic['b'] = 2;
dic.c = 3;
// 遍历;
for (const key in dic) {
if (dic.hasOwnProperty(key)) {
console.log(dic[key]);
}
}
关于更多索引类型的内容,可以参考 Ts 文档 高级类型 中的索引类型和字符串索引签名。
参考:
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论