我正在将我的代码从Javascript转换为Typescript我的代码在Javascript中工作,但它在Typescript中有错误
以下是代码
const jsonData = {
query: "keywords in here",
page: {size: 10, current: 1},
options: {
all: [
{ datetimestart: {from: currentDateTimeInISOString}},
{ price: {from: 0, to: (freeEventsOnly ? 0.1 : 99999999999) }},
],
},
};
if (meetSomeCondition) {
jsonData.options.all.push({ city: domicile }); // <--- try to append another object to array
}如您所见,我有一个名为jsonData的对象,该对象有一个名为options的属性,该对象具有名为all的属性,该属性是多个对象的数组
然后尝试将另一个对象附加到数组中,但出现以下错误

似乎我推送了一个数据类型不同的对象?如何解决这个问题?
发布于 2021-02-05 19:56:06
文字不能是不同的类型。Typescript从文本中的所有数组元素推断出一个联合类型(您可以在错误消息中看到它)。您可以将options上的all定义为Record<string, any>[]
const all: Record<string, any>[] = [
{ datetimestart: {from: currentDateTimeInISOString}},
{ price: {from: 0, to: (freeEventsOnly ? 0.1 : 99999999999) }},
]
const jsonData = {
query: "keywords in here",
page: {size: 10, current: 1},
options: {
all,
},
};
if (meetSomeCondition) {
jsonData.options.all.push({ city: domicile }); // <--- try to append another object to array
}https://stackoverflow.com/questions/66062735
复制相似问题