gpt4 book ai didi

performance - Map 和 {[index : string]: MyObject} in TypeScript? 有什么区别

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

如果我想在 TypeScript 中使用带有类型检查的 string:object 字典,我知道有两种方法可以做到这一点:

const m = new Map<string, MyObject>();
m.set("a", new MyObject("a"));
m.set("b", new MyObject("b"));

const m : {[index: string]: MyObject} = {};
m["a"] = new MyObject("a");
m["b"] = new MyObject("b");

它们各自的优点和缺点是什么?如果有另一种方法来声明和使用 string:MyObject 字典?

最佳答案

详见 this回答(在我之前投票!),在支持 Map 之前,Typescript 中通常使用具有类型键和值的对象(有时称为 HashMap ):

const m : {[index: string]: MyObject} = {};

这种方法的问题是键只能是字符串或数字类型,实际上你使用什么作为键类型并不重要,因为数字/字符串仍然可以互换接受(只有值是强制的) .

Typescript 现在原生支持 ES6 Map 类型,它没有上述键的任何缺点。至于hashmap相对于Map的优势,我看不出有什么。

但是,如果您确实想通过索引运算符与(现在是遗留的)Map 类型进行交互,您可以通过将其包装在 Proxy 中来实现。例如

const map = new Map<string, number>();
// Set the value of "a" using Map's set function
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);

// Now add "b" to the Map with the value of 321 via the Proxy wrapper
mapWrapper["b"] = 321;

你可以看到这个例子正在运行 here .

关于performance - Map<string, MyObject> 和 {[index : string]: MyObject} in TypeScript? 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55801034/

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