0

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

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.