Home > Back-end >  TypeScript Map: Type 'number | undefined' is not assignable to type 'number'
TypeScript Map: Type 'number | undefined' is not assignable to type 'number'

Time:04-23

I have the typescript code below in VS Code,

const hash: Map<string, number> = new Map<string, number>([
    ['Small', 1],
    ['Medium', 2],
    ['Large', 3],
]);
const sz = 'Small';
const num: number = hash.has(sz) ? hash.get(sz) : 0;

It keeps complaining:

Type 'number | undefined' is not assignable to type 'number'. Type 'undefined' is not assignable to type 'number'.

Not sure anything I did wrong here. Doesn't hash.has(sz) already ensure hash.get(sz) won't be undefined?

My current approach is to use const num: number = hash.has(sz) ? hash.get(sz)! : 0; but it doesn't seem to be a graceful to me.

What's the proper way to fix this kind of issue?

CodePudding user response:

const hash: Map<string, number> = new Map<string, number>([
    ['Small', 1],
    ['Medium', 2],
    ['Large', 3],
]);
const sz = 'Small';
const num: number = hash.get(sz) ?? 0;

This should do it. Map.prototype.get returns undefined if it can't find the key, which we can null coalesce into 0.

CodePudding user response:

Try removing the comma from the 3rd element of the array: ['Large', 3]

  • Related