【发布时间】: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;
}
我觉得我走错了路,但我不知道该怎么做。究竟是什么问题?
【问题讨论】:
-
<MqttPublishAnchorPoint>[]表示[] as MqttPublishAnchorPoint,而不是[] as MqttPublishAnchorPoint[]。这可能是出错的原因。 -
啊,谢谢!我这样解决了:
[]。如果你愿意回答这个问题,我可以让你接受答案。
标签: typescript