My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T.
Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it might be undefined.
In the given scenario, I anticipate the variable 'entry' to have the type number|undefined
. Strangely though, Typescript infers it as number
, which appears to be incorrect:
const data: {[index:string]: number} = {
"aa34da": 1,
"basd23": 2,
"as34sf": 5
};
const entry = data["doesn't exist"];
console.log(entry);
Could this be possibly attributed to a bug within the type inference system?
I am acquainted with the ES6 Map that offers a get()
method matching the exact signature I expect. Nevertheless, the Map structure does not integrate well with JSON serialization. As a preference, I would rather stick with using objects.