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.