【问题标题】:Type 'string[]' is not assignable to type 'string'. when using Date object类型 'string[]' 不可分配给类型 'string'。使用 Date 对象时
【发布时间】:2018-09-05 05:37:18
【问题描述】:

我有一个从类/模型 (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'
我该如何解决这个问题?很难找到答案,因为我认为错误太广泛了。

【问题讨论】:

  • 您希望_startDate 是字符串还是字符串数组?
  • 什么是 startDateFormat ?
  • _startDate 是一个字符串,因为 this.projInfo.startDato 是一个字符串。 split 返回一个数组,因此您不能将 _startDate 与数组相等(实际上您可以定义 public _startDate:string|string[]=this.projInfo.startdato,但我认为您不想这样做)

标签: angular typescript casting


【解决方案1】:

当你初始化一个类变量并为其赋值时

public _startDate = this.projInfo.startdato;

并且 this.projInfo.startdato 具有字符串类型,打字稿编译器将假定 _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

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2019-05-12
    相关资源
    最近更新 更多