简体   繁体   中英

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. 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; b: number; }' is not assignable to type '{ 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

Your types are't consistent. You can explicitly tell Map the types it's going to have

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}]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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