Reputation: 30066
I'm using an object to store a map, keys are strings, values have a fixed type T.
When looking up a key in the object, the type inference assigns it the type T.
But it might be undefined.
In the following example, I would expect entry to have the type number|undefined
. But typescript infers the type number
. That doesn't seem correct:
const data: {[index:string]: number} = {
"aa34da": 1,
"basd23": 2,
"as34sf": 5
};
const entry = data["doesn't exist"];
console.log(entry);
Is this a bug in the type inference?
I am aware of the ES6 Map, which offers a get()
method of exactly the signature that I would expect. But Map doesn't play well with JSON serialization. I would prefer to just use objects.
Upvotes: 1
Views: 1304
Reputation: 37938
As you've already figured out, there's no bug in type inference because the data
's type is explicitly set to "object containing number at any string key". So we should let typescript know that value might be undefined
:
declare const data: { [index: string]: number|undefined };
You could also use Record utility to define such a type:
declare const data: Record<string, number | undefined>;
Record<K, T>
Constructs a type with a set of properties K of type T.
Upvotes: 3
Reputation: 30066
After some playing around with the code, I think the proper way to declare a map-like object, where some keys might not point to values is:
const data: {[index:string]: number|undefined} = {
"aa34da": 1,
"basd23": 2,
"as34sf": 5
}
const entry = data["doesn't exist"];
Upvotes: 0