嵌套打字稿地图类型 [英] Nested Typescript Map Type
问题描述
使用Typescript 3.5.1,我似乎无法获取要编译的值的类型.对于以下内容:
With Typescript 3.5.1, I can't seem to get the type of values to compile. For the following:
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的值泛型看起来像联合类型?
Is this a compiler bug, or am I doing something wrong to make the Map's value generic look like a union type?
推荐答案
我很确定这不是错误.Typescript将您右侧的类型缩小为 {ok:string,nah ?: undefined} |{ok ?:未定义,nah:字符串}
,因为您有两个缺少另一个属性的对象.如果访问"nah",则只有"ok"的将返回未定义的内容,反之亦然.
I'm pretty sure this is not a bug. Typescript narrows the type of your right side down to {ok: string, nah?: undefined} | {ok?: undefined, nah: string}
, since you have two objects that are missing the property of the other. The one that has only "ok" will return undefined if "nah" is accessed and vice-versa.
这意味着初始类型 {[key:string]:string}
不再有效,因为属性可以返回字符串("so"和"right"是字符串的子类型)或未定义.
This means that the initial type {[key: string]: string}
is not valid anymore, because the properties can either return a string ('so' and 'right' are subtypes of string) or undefined.
最简单的方法是使用 Map< foo,{[key:string]:string |未定义}>
.
编辑:更正了推断的类型-感谢jcalz指出了这一点!
Corrected the inferred type - thanks to jcalz for pointing that out!
这篇关于嵌套打字稿地图类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!