flyingbee
flyingbee

Reputation: 621

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

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?

Upvotes: 2

Views: 4529

Answers (2)

Simon Meskens
Simon Meskens

Reputation: 968

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.

Upvotes: 4

Jim VanPetten
Jim VanPetten

Reputation: 436

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

Upvotes: -1

Related Questions