如何在打字稿中创建不同类型值的地图

How to create a Map of different type of value in typescript

我已经开始学习 Typescript,我试图创建一个具有不同类型值的地图,但它不起作用。 我尝试在定义 Map 时直接将 stringnumber 作为选项,但抛出错误,我们无法将 number 映射到 string

const testMap: Map<string,string|number> = new Map([["a", "test1"],["b","test2"],["c",1]]);

求推荐。

Playground

Typescript 在这种情况下无法正确推断值类型,但您可以在调用 Map 的构造函数时明确指定 generic type parameters

const testMap = new Map<string, string | number>([["a", "test1"], ["b", "test2"], ["c", 1]]);

Playground