将类型 'Map<string, string>' 转换为类型 '{ [key: string]: string; }' 在打字稿中

Mik*_*asa 4 typescript

我是打字稿新手。我有一张打字稿地图,如下所示:

const mapping = new Map<string, string>();
mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion')
...
Run Code Online (Sandbox Code Playgroud)

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

如何在打字稿中做到这一点?

brc*_*-dd 7

只需执行以下操作:

Object.fromEntries(mapping)
Run Code Online (Sandbox Code Playgroud)

参考:


完整示例:

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)
Run Code Online (Sandbox Code Playgroud)