简体   繁体   English

TypeScript for循环中的类型声明

[英]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? 有没有一种更整洁/更优雅的方法来将day为适当的类型,而不是(<{P: string}>day).P而在这种情况下,我不通过any类型从我通过underscore.js接收day对象findWhere命令?

If I just write let period of day.P it results in this error: 如果我只写let period of day.P则会导致此错误:
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 如果问题出在_.findWhere ,它可能_.findWhere返回的结果声明为一个对象(我没有检查过),则可以使用as语法_.findWhere结果

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

Since it seems your only interested in the "P" member for this task. 由于似乎您仅对此任务的“ P”成员感兴趣。 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). 我个人建议在开始for循环之前为整个可读性以及关注点分离(在Moment实体和工作数据之间有明显区别)开始之前,映射整个Day数组并进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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