Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(TypeScript2) How do you loop through an array of interface type?

While using a for loop my let object has the type of string, even though the object I am iterating through is of a type defined in an interface.

Below is the code I am using. When trying to access mapping.attribute which is defined on the interface as a string, I get the error [Property 'attribute' does not exist on type 'string'.]

I have the following interface and function :

interface IMapping {
    attribute: string;
    property: string;
}

mapAttributes(mappings: IMapping[], values) {            
    for (let mapping in mappings) {
        if (mapping.hasOwnProperty("attribute")) {
            console.log(this.attributes.find(attribute => attribute.name === mapping.attribute).value);
        }
    }
}

How should the for loop be defined so that I can use a property that has been defined in my interface?

like image 796
Ben Temple-Heald Avatar asked Dec 15 '16 11:12

Ben Temple-Heald


People also ask

How do I iterate over an interface?

To iterate over interface properties in TypeScript, we can use the Object. keys method. const Activity = { id: "", title: "", body: "", json: {}, }; type Activity = typeof Activity; const headers: Array<Object> = Object. keys(Activity).

Can an array type be an interface?

Interface as array type​An interface can also define the type of an array where you can define the type of index as well as values.

Can we use loop in angular?

The for–in loop is for looping over object properties. The for–of loop is for looping over the values in an array. for–of is not just for arrays. It also works on most array-like objects including the new Set and Map types which we will cover in the next lecture.


2 Answers

I was able to run your example when replacing

for (let mapping in mappings) {

with

for (let mapping of mappings) {
like image 95
Blablalux Avatar answered Nov 23 '22 19:11

Blablalux


This occurred due to for..of vs. for..in statements

Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

Here is an example that demonstrates this distinction:

let list = [4, 5, 6];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

for (let i of list) {
   console.log(i); // "4", "5", "6"
}
like image 23
Rukshan Dangalla Avatar answered Nov 23 '22 18:11

Rukshan Dangalla