不能分配给类型“any[]”的类型对象数组

时间:2021-02-17 17:59:12

标签: typescript

我想根据类型定义一个对象。在该对象中是一个由也对应于给定类型的元素组成的数组。但是,我只想稍后将元素推送到此数组并将其初始化为空。但它给了我一个错误,我无法弄清楚。我的 app.ts 中有以下几行:

const publishObject: MqttPublishObject = {
                        IsTurnedOff: detail.isTurnedOff,
                        processType: detail.processType.name === "linear" ? 0 : 1,
                        anchorPoints: <MqttPublishAnchorPoint>[]
                      };

我收到此错误:

src/app/app.ts(51,25): error TS2322: Type 'MqttPublishAnchorPoint' is not assignable to type 'any[]'.
src/app/app.ts(51,39): error TS2352: Conversion of type 'undefined[]' to type 'MqttPublishAnchorPoint' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

typedef 位于以下文件中:

mqttPublishObject.ts

export interface MqttPublishObject {
   IsTurnedOff : boolean;
   processType : number;
   anchorPoints : MqttPublishAnchorPoint[];
}

mqttPublishAnchorPoint.ts

export interface MqttPublishAnchorPoint {
    hour: number;
    minute: number;
    second: number;
    intensity: number;
}

我觉得我的做法是错误的,但我不知道该怎么做。究竟是什么问题?

1 个答案:

答案 0 :(得分:1)

这些错误基本上告诉你两件事:

  • 第一个错误意味着您正在尝试将 MqttPublishAnchorPoint 类型的值分配给 MqttPublishAnchorPoint[] 类型的字段。这意味着 TypeScript 以某种方式将您的数组视为不是一个数组,而是一个 MqttPublishAnchorPoint
  • 原因由第二个错误给出:您试图将数组类型 (undefined[]) 的某个值强制转换为 MqttPublishAnchorPoint,而 TypeScript 无法理解此断言,因为类型不重叠。

这两个错误的核心原因是强制转换:<T>[] 表示 [] as T,而不是 [] as T[],即强制转换应用于数组,而不是其内部类型。解决方法很简单:

const publishObject: MqttPublishObject = {
  IsTurnedOff: detail.isTurnedOff,
  processType: detail.processType.name === "linear" ? 0 : 1,
  anchorPoints: <MqttPublishAnchorPoint[]>[],
};

Playground(通过删除与重现错误无关的所有内容来简化)。


但是,在这种情况下,您永远不需要演员表。由于变量是强类型的,TypeScript 能够推断数组类型而无需在值附近显式指定它:

const publishObject: MqttPublishObject = {
  IsTurnedOff: detail.isTurnedOff,
  processType: detail.processType.name === "linear" ? 0 : 1,
  anchorPoints: [], // inferred as MqttPublishAnchorPoint[]
};