7

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?

2 Answers 2

17

I was able to run your example when replacing

for (let mapping in mappings) {

with

for (let mapping of mappings) {
Sign up to request clarification or add additional context in comments.

Comments

4

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.