简体   繁体   中英

Type declaration in TypeScript for loop

Is there a neater/more elegant way to cast day as the appropriate type, rather than (<{P: string}>day).P without resorting to the any type in this instance where I receive a day object from underscore.js via the findWhere command?

If I just write let period of day.P it results in this error:
TS2339:Property 'P' does not exist on type '{}'.

let day = _.findWhere(this.availabilityDays, {D: moment($scope.model.BookDate).format('YYYY-MM-DD')});
this.$scope.BookingPeriods.splice(0);
for (let period of (<{P: string}>day).P) {
    this.$scope.BookingPeriods.push(period);
}

Use an interface

interface Day {
  P: string;
}

// in the class
public availabilityDays: Day[];

if the problem is in _.findWhere , which possibly declares returned result as an object (I didn't check that), then you can cast the result using as syntax

let day: Day = _.findWhere(this.availabilityDays, condition) as Day;

Since it seems your only interested in the "P" member for this task. I personally would recommend mapping over the day array and doing the conversion before beginning the for loop for readability as well as separation of concerns (clear distinction between your Moment entity, and the working data).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM