gpt4 book ai didi

typescript - 将类型 'Map' 转换为 Typescript 中的类型 '{ [key: string]: string; }'

转载 作者:行者123 更新时间:2023-12-02 01:58:00 29 4
gpt4 key购买 nike

我是 typescript 的新手。我有一张 typescript map ,如下所示:

const mapping = new Map<string, string>();
mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion')
...

我正在尝试将映射转换为类型 '{ [key: string]: string; }'

如何在 typescript 中做到这一点?

最佳答案

简单地做:

Object.fromEntries(mapping)

引用:


Complete example:

const mapping = new Map<string, string>()

mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion')

console.log(mapping)

// { [key: string]: string } is same as Record<string, string>
const record: { [key: string]: string } = Object.fromEntries(mapping)

console.log(record)

关于typescript - 将类型 'Map<string, string>' 转换为 Typescript 中的类型 '{ [key: string]: string; }',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69401951/

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