【问题标题】:What's the difference between Map<string, MyObject> and {[index: string]: MyObject} in TypeScript?TypeScript 中的 Map<string, MyObject> 和 {[index: string]: MyObject} 有什么区别?
【发布时间】:2019-09-12 00:54:41
【问题描述】:

如果我想在 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 字典?

【问题讨论】:

    标签: performance typescript dictionary


    【解决方案1】:

    正如this 回答中详细说明的那样(在我之前投票!),在 Typescript 支持 Map 之前,通常使用具有类型化键和值的对象(有时称为哈希图):

    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

    【讨论】:

    • 有什么方法可以通过 [] 操作符使用 Map 吗?
    • @lebed2045 您可以通过 [] 运算符将 Map 包装在 JS 代理中来使用它。 Here's 我写的一个例子。我同意 JavaScript Map 应该有对这个操作符的原生支持。如果您希望我将其添加到我的答案中,请告诉我(您可以说这应该是一个单独的问题)。
    • 是的,如果您可以将此添加到答案中,我认为这对其他人来说很有价值。
    • @lebed2045 完成!
    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多