正如
this答案中详细说明的那样(在我的回答之前点赞!),在Typescript支持Map之前,一个具有类型键和值的对象(有时称为哈希表)是常用的:
const m : {[index: string]: MyObject} = {};
这种方法的问题在于键只能是字符串或数字类型,而实际上使用什么类型作为键类型并不重要,因为数字/字符串仍然可以互换使用(只有值被强制执行)。
Typescript现在原生支持ES6 Map类型,它没有上述关于键的任何缺点。至于哈希映射相对于Map的优势,我看不出来。
但是,如果您确实想通过索引运算符与(现在的遗留)Map类型交互,您可以通过将其包装在
代理中来实现。
const map = new Map<string, number>();
map.set("a", 123);
const handler = {
get: (target: Map<string, number>, name: string) => { return target.get(name)},
set: (target: Map<string, number>, name: string, value: number) => {target.set(name, value)}
};
const mapWrapper = new Proxy(map, handler);
mapWrapper["b"] = 321;
你可以在
这里看到此示例运行。