[英]Why does this map declaration throw a type error?
I tried declaring a variable where each key in the map is an array of objects.我尝试声明一个变量,其中 map 中的每个键都是一个对象数组。 for some reason the act of making the value an array throws a type error.
由于某种原因,将值设为数组的行为会引发类型错误。
this is allowed:这是允许的:
var map = new Map([
['a', {c: 1}],
['b', {c: 1, d: 1}]
])
this is not allowed:这是不允许的:
var map = new Map([
['a', [{c: 1}]],
['b', [{c: 1, d: 1}]]
])
the second piece of code will throw this error: Type '{ a: number;第二段代码会抛出这个错误:Type '{ a: number; b: number;
b:号码; }' is not assignable to type '{ a: number;
}' 不可分配给类型 '{ a: number; }'
}'
why is the first piece of code allowed but the second not allowed?为什么允许第一段代码但不允许第二段代码? i would expect to be allowed to have different types on each key of my map
我希望被允许在我的 map 的每个键上使用不同的类型
Your types are't consistent.你的类型不一致。 You can explicitly tell Map the types it's going to have
您可以明确告诉 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.