I'm looping over data in an array and want to cast my looped item to an extended interface (it has an extra label field). What can I recast it? to a "PersonLabel"?
for (const person of people) {
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
I tried approaches such as this (does not compile):
for (const person:PersonLabel of people) {
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
and this (does not compile)
for (const person of people) {
person = typeof PersonLabel;
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
You can use <Type> or as Type.
In your case this means:
person = <PersonLabel> person;
or the prefered way with as:
person = person as PersonLabel;
Remember to change const person to let person as you cannot reassign a const.
Or you can cast it already in the for loop like this:
for (const person of people as PersonLabel[]) { //<PersonLabel[] people should work as well...
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
This assumes PersonLabel derives from the class Person. Otherwise you cannot cast the types (like you can't cast a number to string).
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