You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Typescript中如何将Map<string, string>转为{ [key: string]: string; }类型

Typescript中将Map实例转换为普通对象的实现方法

你可以根据运行环境支持的语法标准选择以下两种实现方案:

  • 方案1:ES2019及以上环境使用Object.fromEntries
    这是最简洁的实现方式,Typescript可以自动推导转换后的对象类型,无需额外类型断言:
    const mapping = new Map<string, string>();
    mapping.set('fruit', 'apple')
    mapping.set('vegetable', 'onion')
    
    // 直接转换,类型自动匹配{ [key: string]: string }
    const resultObj = Object.fromEntries(mapping);
    
  • 方案2:低版本兼容实现(支持ES6及以上环境)
    如果你需要兼容更低的运行环境,可以手动遍历Map实例完成赋值:
    const mapping = new Map<string, string>();
    mapping.set('fruit', 'apple')
    mapping.set('vegetable', 'onion')
    
    const resultObj: { [key: string]: string } = {};
    for (const [key, value] of mapping) {
      resultObj[key] = value;
    }
    

注意:两种方案均默认你传入的Map实例键为字符串类型,若存在非字符串键,转换为对象时会自动调用toString()方法处理键名。

内容的提问来源于stack exchange,提问作者Mikasa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:57:03