Categories
TypeScript Answers

How to enumerate properties on an object with TypeScript?

Spread the love

Sometimes, we want to enumerate properties on an object with TypeScript.

In this article, we’ll look at how to enumerate properties on an object with TypeScript.

How to enumerate properties on an object with TypeScript?

To enumerate properties on an object with TypeScript, we can use the for-of loop and the Object.entries method.

For instance, we write

class StationGuide {
  station1: any;
  station2: any;
  station3: any;

  constructor() {
    this.station1 = null;
    this.station2 = null;
    this.station3 = null;
  }
}

const a = new StationGuide();

for (const [key, val] of Object.entries(a)) {
  console.log(key, val);
}

to create a StationGuide class instance and assign it to a.

Then we convert the object to an array of key-value pair arrays with Object.entries.

Then we loop through the array of key-value pair arrays with the for-of loop.

We destructure the key and val key and value from each array and log their values.

Conclusion

To enumerate properties on an object with TypeScript, we can use the for-of loop and the Object.entries method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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