类型'string []'不能分配给'string'类型。使用Date对象时

问题描述 投票:0回答:1

我有从类/模型(projInfo)获取数据的组件,包括日期对象。我需要使用日期(日/月/年)格式的不同部分,以便我需要将它们分解并将它们放入数组中。

我似乎无法将Date对象解析为string []类型。这就是我所拥有的:

  public _startDate = this.projInfo.startdato; //.toString();

  @Input()
  set startDate(startDate: string) {
    // remove commas then split into array
    const d: string = this.startDateFormat.replace(',', '');
    this._startDate = d.split(' ');
  }

最后一行的“this._startDate”提供了错误Type 'string[]' is not assignable to type 'string'。 我该如何解决这个问题?搜索答案很难,因为我认为错误太宽泛了。

angular typescript casting
1个回答
0
投票

初始化类变量并为其赋值时

public _startDate = this.projInfo.startdato;

并且this.projInfo.startdato具有类型字符串,typescript编译器也将_startDate的类型视为字符串。由于字符串的split方法:String.prototype.split()将返回编译器抱怨的数组。

您必须确定_startDate变量应该是哪种类型。我不知道this.projInfo.startdato是什么,所以我不能给你任何解决方案。

通常,您可以使用以下类型初始化变量:

public _startDate: Array<string> = [this.projInfo.startdato];

打字稿中的类型转换会起作用

this._startDate = <string> d.split(' '); // I guess this still won't work in this case
© www.soinside.com 2019 - 2024. All rights reserved.