打字稿 - 类型中缺少索引签名 - 上下文键入

时间:2017-06-19 11:49:34

标签: typescript typescript-typings

我有以下类和子类

export class FlightInfoModel {
    carrierName?: string;
    originCode?: string;
    destCode?: string;
    flightDetails: FlightSegmentEntity[];

    constructor() {
        this.carrierName = "";
        this.originCode = "";
        this.destCode = "";
        this.flightDetails = new Array<FlightSegmentEntity>();
    }
}

export class FlightSegmentEntity {
  CarrierCode: string;
  FlightNo: string;
  Aircraft: string;

  OriginCode: string;
  DestinationCode: string;

  DepartureDate: string;
  ArrivalDate: string;

  FlightDuration: number;
  StopOverDuration: string;

  constructor() {
    this.CarrierCode = "";
    this.FlightNo = "";
    this.Aircraft = "";
    this.OriginCode = "";
    this.DestinationCode = "";
    this.DepartureDate = "";
    this.ArrivalDate = "";
    this.FlightDuration = -1;
    this.StopOverDuration = "";
  }

我使用Typescript和UnderscoreJS编写以下函数。 flight是FlightInfoModel对象,flightDetails是FlightSegmentEntity []

_.reduce(flight.flightDetails,
function(memo, seg){ return memo + seg.FlightDuration + seg.StopOverDuration; },
0)

下划线函数接受数组集合,但我不断收到以下错误

错误TS2345:类型&#39; FlightSegmentEntity []&#39;的参数不能分配给参数 类型&#39;字典&lt; {}&gt;&#39;。   类型为&#39; FlightSegmentEntity []&#39;。

中缺少索引签名

我已经阅读了很多关于Typescript需要的上下文输入,并尝试这样做但无济于事。顺便说一下,我使用的是Typescript 2.3.4

1 个答案:

答案 0 :(得分:0)

您粘贴的代码缺少parseInt(seg.StopOverDuration)

const total = _.reduce(flight.flightDetails, (t, seg) => {
    return t + (seg.FlightDuration + parseInt(seg.StopOverDuration));
}, 0);

但错误是关于字典:

  

类型&#39; FlightSegmentEntity []&#39;不能分配给&#39;词典&lt; {}&gt;&#39;类型的参数。

您在粘贴的代码中没有Dictionary<T>,因此我猜您需要分享更多详细信息。

更新

我测试了以下内容并且无误地运行:

import * as _ from "underscore";

class FlightInfoModel {

    public carrierName: string;
    public originCode: string;
    public destCode: string;
    public flightDetails: FlightSegmentEntity[];

    public constructor() {
        this.carrierName = "";
        this.originCode = "";
        this.destCode = "";
        this.flightDetails = new Array<FlightSegmentEntity>();
    }
}

class FlightSegmentEntity {
  public CarrierCode: string;
  public FlightNo: string;
  public Aircraft: string;

  public OriginCode: string;
  public DestinationCode: string;

  public DepartureDate: string;
  public ArrivalDate: string;

  public FlightDuration: number;
  public StopOverDuration: string;

  public constructor() {
    this.CarrierCode = "";
    this.FlightNo = "";
    this.Aircraft = "";
    this.OriginCode = "";
    this.DestinationCode = "";
    this.DepartureDate = "";
    this.ArrivalDate = "";
    this.FlightDuration = -1;
    this.StopOverDuration = "";
  }
}

const flight = new FlightInfoModel();

const result = _.reduce(flight.flightDetails, (memo, seg) => {
        return memo + seg.FlightDuration + parseInt(seg.StopOverDuration);
    },
    0
);

alert(result);