Reputation: 833
I'm very confused about how Map entries are managed on TypeScript
Consider the following code:
const foo = new Map();
foo.set(1, "1");
console.log('foo=', foo);
const myValue = foo.get(1) as number;
console.log('foo as number %i ', myValue );
console.log('foo as string %s ', myValue );
Gives me NaN with %i and works fine with %s
Change the code to
const myValue = +foo.get(1);
Works for me but looks like a ugly workaround.
What is the correct way to parse a get() on a Map object?
Upvotes: 0
Views: 1257
Reputation: 33061
Just use generics and parseInt:
type StirngNumber<T extends number>=`${T}`
const foo = new Map<number, StirngNumber<number>>();
foo.set(1, "1");
const val = foo.get(1)
const myValue = val ? parseInt(val, 10) : 'can find a value' // string | undefined
console.log(myValue);
Upvotes: 1