Alex l.
Alex l.

Reputation: 273

How to tell typescript that map.get will always return a value?

map is an instance of Map. In this code I want to create new [key, value] pair if it doesn't already exist and then edit propertyInValue

if (!map.has(key)) { 
    map.set(key, new Value())
}
map.get(key).propertyInValue = doSomething()

I get an error Object is possibly 'undefined' on map.get(key)

Can I somehow tell TypeScript to not worry about it? Can it be done in tsconfig.json?

Upvotes: 12

Views: 4762

Answers (1)

Alex l.
Alex l.

Reputation: 273

I figured it out.

Non-null assertion saves the day!

map.get(key)!.propertyInValue = doSomething()

Also possible to set "strictNullChecks": false in tsconfig.json

Upvotes: 10

Related Questions