Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript casting / assertion with a for loop

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);
}
like image 542
SD Dev Avatar asked Apr 29 '26 23:04

SD Dev


1 Answers

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

like image 165
Spitzbueb Avatar answered May 01 '26 22:05

Spitzbueb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!