繁体   English   中英

为什么这个 map 声明会引发类型错误?

[英]Why does this map declaration throw a type error?

我尝试声明一个变量,其中 map 中的每个键都是一个对象数组。 由于某种原因,将值设为数组的行为会引发类型错误。

这是允许的:

var map = new Map([
            ['a', {c: 1}],
            ['b', {c: 1, d: 1}]
        ])

这是不允许的:

var map = new Map([
            ['a', [{c: 1}]],
            ['b', [{c: 1, d: 1}]]
        ])

第二段代码会抛出这个错误:Type '{ a: number; b:号码; }' 不可分配给类型 '{ a: number; }'

为什么允许第一段代码但不允许第二段代码? 我希望被允许在我的 map 的每个键上使用不同的类型

你的类型不一致。 您可以明确告诉 Map 它将具有的类型

interface MapValue {
  c: number;
  d?: number;
}

const map = new Map<string, MapValue[]>([
  ['a', [{ c: 1 }]],
  ['b', [{ c: 1, d: 1 }]]
])

// or

interface MapValue {
  c: number;
  d: number;
}

const map = new Map<string, MapValue[]>([
  ['a', [{ c: 1 } as MapValue]],
  ['b', [{ c: 1, d: 1}]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM