If you're trying to loop through properties of an Interface
, you'll hit a roadblock because they are only accessible at compile time. However, one workaround is to create an object based on your Interface
and then iterate over its properties
.
interface Person {
name: string;
age: number;
}
const personFields: Person = {
name: "John",
age: 30,
};
let newObject = {};
Object.keys(personFields)
.forEach(key => {
newObject = {...newObject, [key]: key};
})
console.log(newObject);
Output:
[LOG]: {
"name": "name",
"age": "age"
}
Alternatively, you can utilize the ts-transformer-key library mentioned here