【问题标题】:Array of typed objects not assignable to type 'any[]'类型化对象数组不可分配给类型“任何 []”
【发布时间】:2021-02-17 17:59:12
【问题描述】:

我想根据类型定义一个对象。在该对象内是一个数组,该数组由也对应于给定类型的元素组成。但是,我只想稍后将元素推送到该数组并暂时将其初始化为空。但这给了我一个错误,我无法弄清楚。我的 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;
}

我觉得我走错了路,但我不知道该怎么做。究竟是什么问题?

【问题讨论】:

  • &lt;MqttPublishAnchorPoint&gt;[] 表示[] as MqttPublishAnchorPoint,而不是[] as MqttPublishAnchorPoint[]。这可能是出错的原因。
  • 啊,谢谢!我这样解决了:[]。如果你愿意回答这个问题,我可以让你接受答案。

标签: typescript


【解决方案1】:

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

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

这两个错误的核心原因是转换:&lt;T&gt;[] 表示 [] 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[]
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2020-04-02
    • 2018-02-24
    相关资源
    最近更新 更多