GONeale
GONeale

Reputation: 26494

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

Upvotes: 0

Views: 675

Answers (2)

Evgeniy Malyutin
Evgeniy Malyutin

Reputation: 1387

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;

Upvotes: 2

iHazCode
iHazCode

Reputation: 771

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

Upvotes: 0

Related Questions