简体   繁体   English

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

[英]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.

相关问题 打字稿声明:为什么这会引发错误 - Typescript declaration: why does this throw an error TypeScript编译器不会在缺少声明时引发错误 - TypeScript compiler does not throw error on missing declaration 为什么 TypeScript 不会为未定义的类型抛出编译错误 - Why does TypeScript not throw a compile error for an undefined type 为什么枚举上的 switch 语句会抛出“无法与类型相比”的错误? - Why does a switch statement on an enum throw 'not comparable to type' error? 为什么 Typescript 会抛出错误信息:类型上不存在属性? - Why Typescript throw error message: Property does not exist on type? 当 function 参数类型不匹配时,为什么 TypeScript 不抛出错误? - Why does TypeScript not throw an error when the function argument type is mismatched? 为什么 TypeScript 会抛出错误:TS2339:“EventTarget”类型上不存在属性“错误” - Why does TypeScript throw the error: TS2339: Property 'error' does not exist on type 'EventTarget' 为什么 TypeScript 在检查联合类型的 if 语句中会抛出错误,就好像它只是文字类型一样? - Why does TypeScript throw an error in an if statement checking an Union Type as if it's just a Literal Type? 泛型打字稿,为什么这段代码会抛出错误 Type '{}' cannot be assigned to a type? - Generics typescript, why does this code throw an error Type '{}' cannot be assigned to a type? Typescript union 类型不抛出错误 - Typescript union type does not throw error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM