首页 > 解决方案 > 在 TypeScript 中获取日期的周数

问题描述

我有一个包含其他类的类

export class Sensor {
  public id: string;
  public label: string;
  public measures: Measure[];
  constructor(dbDate){

  }
}

export class Message {
  public id: string;
  public arrivalTimestamp: Date;
  public sensors: Sensor[];
  constructor(dbData: any) {
      this.id= dbData.id;
      this.arrivalTimestamp= dbData.value.timestamp ;
      this.sensors = new Sensor(dbData);
  }
}

我实际上面临问题:Type 'Sensor' is not assignable to type 'Sensor[]'. Property 'length' is missing in type 'Sensor'.

sensors有一个类型,Array of Sensor但我在构造函数中影响它的是 type Sensor

我试图添加刹车new Sensor[](dbData);,但它不起作用我收到 VS Code 警告消息An element access expression should take an argument.

标签: javascripttypescriptoop

解决方案


您想要的只是拥有一个元素的数组,而不是“传感器阵列”类型的元素。

在 javascript 中,您可以动态创建一个数组,只需用方括号将变量括起来:

this.sensors = [new Sensor(dbData)];

这样一来this.sensors,总会有一个元素。否则,您也可以将sensors变量初始化为空数组:

public sensors: Sensor[] = [];

然后使用推送方法:

this.sensors.push(new Sensor(dbData));

此方法会将元素添加到数组中


推荐阅读