简体   繁体   中英

typescript: declare type of map-like object

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.

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.

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"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM