Reputation: 1998
I found a post with a similar name although the problem is different.
I'm trying to count the number of occurrences of an attribute in a list of a objects.
let objArray = [{state: 'North Carolina'},{state: 'Florida'}]
let res = new Map<string, number>();
for (let obj of objArray) {
if (res.get(obj.state)) {
res.set(obj.state, res.get(obj.state)+1)
} else {
res.set(obj.state, 1)
}
}
But typescript flags res.get(obj.state) + 1
because res.get(obj.state)
may be undefined
(which I don't think is possible).
I'd also be equally fine with let res = {}
but when I write analogous code for that typescript doesn't like trying to index res
by string
.
I'm kinda at a loss for what typescript expects me to do to accomplish my simple task.
Upvotes: 1
Views: 457
Reputation: 7564
The TypeScript compiler should be happy if you extract the repeated use of res.get(obj.state)
into a variable:
let objArray = [{state: 'North Carolina'},{state: 'Florida'}]
let res = new Map<string, number>();
for (let obj of objArray) {
const state = res.get(obj.state);
if (state) {
res.set(obj.state, state+1)
} else {
res.set(obj.state, 1)
}
}
Upvotes: 5