1

Is there some way to have TypeScript understand that the value retrieved from this map is not undefined?


const stringToDecimal = new Map<string, number>([
    ["one", 1],
    ["two", 2],
]);

console.log(stringToDecimal.get("one") + 5);  // Error about being possibly undefined

It seems you can't use const assertions with Map, and also ReadonlyMap didn't work.

Garrett
  • 4,007
  • 2
  • 41
  • 59
  • 1
    You would either have to use `!` or extend `Map`. – kelsny Nov 15 '22 at 23:01
  • 1
    Here's how extending Map would look like: https://tsplay.dev/WPpqYW – kelsny Nov 15 '22 at 23:09
  • 1
    `Map` is not specific enough for you; as caTS says, you could make your own custom `Map` interface.... like [this](https://tsplay.dev/NVbqvN), as mentioned in the answer to the [linked question](https://stackoverflow.com/questions/54907009/typescript-how-can-i-make-entries-in-an-es6-map-based-on-an-object-key-value-ty). – jcalz Nov 16 '22 at 00:43

0 Answers0