【发布时间】:2021-11-04 21:59:52
【问题描述】:
使用 Typescript 4.5.0,我似乎无法获得要编译的值的类型。对于以下内容:
type foo = 'a' | 'b'
const x: Map<foo, {[key: string]: string}> = new Map([
['a', {'ok': 'so'}],
['b', {'nah': 'right'}]
])
tsc 吐了
const x: Map<foo, {
[key: string]: string;
}>
Type 'Map<"a" | "b", { 'ok': string; 'nah'?: undefined; } | { 'nah': string; 'ok'?: undefined; }>' is not assignable to type 'Map<foo, { [key: string]: string; }>'.
Type '{ 'ok': string; 'nah'?: undefined; } | { 'nah': string; 'ok'?: undefined; }' is not assignable to type '{ [key: string]: string; }'.
Type '{ 'ok': string; 'nah'?: undefined; }' is not assignable to type '{ [key: string]: string; }'.
Property ''nah'' is incompatible with index signature.
Type 'undefined' is not assignable to type 'string'.
这是编译器错误,还是我做错了什么使 Map 的值泛型看起来像联合类型?
【问题讨论】:
-
索引签名和
undefined值有点奇怪...在这种情况下,我会说您应该使用{[key: string]: string | undefined}类型或尝试new Map<foo, {[k: string]: string]}>...但我'我想知道你的用例是什么。我通常使用{[k: string]: SomeType | undefined},因为不太可能每个可能的键都有一个值 -
据我所知,当types unions of object literal types were improved 时,这将是一个一直到 TS2.7 的错误。
-
如果您可以扩展您的用例(您打算如何读取/写入此地图?)我可以将这些 cmets 转换为答案。
标签: typescript generics union-types