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?
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).
Interface as array typeAn interface can also define the type of an array where you can define the type of index as well as values.
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.
I was able to run your example when replacing
for (let mapping in mappings) {
with
for (let mapping of mappings) {
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With