Home » Web » TypeScript » TypeScript and Object.Entries

TypeScript and Object.Entries

If you are using a dictionary or map in TypeScript you may want to know how many elements are mapped. This can be done with Object.Entries(myMappedObject).length. However, the default Typescript configuration won’t let use this latest function because it’s only available in EcmaScript 2017. To get access to it, you need to change the tsconfig.json. Tsconfig.json has a portion called “lib” which increments TypeScript with libraries. To have access to Object.Entries, you need to add “es2017.object”.

    "lib": [
      "es6",
      "dom",
      "es2017.object" 
    ]

If you are curious about the TypeScript generic way to have a dictionary, you can use this interface:

export interface MyMap<T> {
    [id: string]: T;
}

From there you can do:

const c: MyMap<MyObject> = {};
c["myId1"] = myObject1;
c["myId2"] = myObject2;
c["myId3"] = myObject3;
const numberOfElementInDictionary = Object.entries(c).length;

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon.

Leave a Reply

Your email address will not be published. Required fields are marked *