typescript casting / assertion with a for loop

9k views Asked by At

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);
}
2

There are 2 answers

0
Titian Cernicova-Dragomir On

You could try:

for (const person of people as PersonLabel[]) {
  person.label = `${person.namespace}:${person.name}`;
  this.peopleList.push(person);
}
0
Spitzbueb On

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).