Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript Map: Type 'number | undefined' is not assignable to type 'number'

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading