Home > database >  How to loop through properties of an object defined with an interface in typescript?
How to loop through properties of an object defined with an interface in typescript?

Time:10-21

In typescript, if I have an interface like this:

interface A {
    prop1:string;
    prop2:string;
}

var a:A = {
    prop1:"hello", 
    prop2:"world"
};

How can I loop through its properties in this fashion:

for(var prop in a) {
    console.log(a[prop]);
}

This would complain because the A interface doesn't allow to index strings.

How can I resolve it without adding a hacky things like [prop:string]:string;?

Thanks

CodePudding user response:

You could declare prop outside of the for-loop and asign a type to it as we cannot use type declarations inside of loop conditions.

interface A {
    prop1:string;
    prop2:string;
}

let a: A = {
    prop1:"hello", 
    prop2:"world"
};

let prop: keyof A;
for (prop in a) {
  console.log(a[prop]);
}
  • Related