Get the length of an Object in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 23, 2022

banner

Photo from Unsplash

Get the length of an Object in TypeScript #

To get the length of an object in TypeScript:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Access the length property on the array of keys.
  3. The length property will return the number of key-value pairs in the object.
index.ts
interface Person { id: number; name: string; age: number; } const obj: Person = { id: 1, name: 'Tom', age: 30 }; // 👇️ const length: number const length = Object.keys(obj).length; console.log(length); // 👉️ 3

We used the Object.keys method to get an array of the object's keys.

The only parameter the method takes is the object, for which the keys are returned.

index.ts
// 👇️ ['id', 'name'] console.log(Object.keys({ id: 1, name: 'Tom' }));
The last step is to access the length property on the array to get the number of key-value pairs in the object.

An alternative approach is to initialize a length variable, set it to 0 and use a for...in loop to iterate over the object.

index.ts
interface Person { id: number; name: string; age: number; } const obj: Person = { id: 1, name: 'Tom', age: 30 }; let length = 0; for (const key in obj) { if (obj.hasOwnProperty(key)) { length += 1; } } console.log(length); // 👉️ 3

The for...in loops iterates over the object's enumerable properties, including the inherited ones.

This is why we had to use the Object.hasOwnProperty method to check if the property exists directly on the object or is inherited.

We only increment the length variable if the property exists directly on the object.

The second approach is definitely more verbose and indirect than the first, however you might see it in older codebases.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.