Categories
TypeScript Answers

How to iterate over interface properties in TypeScript?

Spread the love

Sometimes, we want to iterate over interface properties in TypeScript.

In this article, we’ll look at how to iterate over interface properties in TypeScript.

How to iterate over interface properties in TypeScript?

To iterate over interface properties in TypeScript, we can use the Object.keys method.

For instance, we write

const Activity = {
  id: "",
  title: "",
  body: "",
  json: {},
};

type Activity = typeof Activity;
const headers: Array<Object> = Object.keys(Activity).map((key) => {
  return { text: key, value: key };
});

to define the Activity object.

Then we call Object.keys with Activity to return an array of non-inherited keys in Activity.

And then we call map with a callback that maps each key to the values we want.

We set headers to type Array<Object> so that the TypeScript compiler knows that headers is an array of objects.

Conclusion

To iterate over interface properties in TypeScript, we can use the Object.keys 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 *