Patrick Desjardins Blog
Patrick Desjardins picture from a conference

TypeScript and Object.Entries

Posted on: 2017-11-30

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;