Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am converting my code from Javascript to Typescript my code below works in Javascript, but it has an error in Typescript

here is the code

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
}

as you can see, I have an object called jsonData, and this object has a property called options which is an object that has property called all that is an array of multiple object

and then try to append another object to array, but I have this error

enter image description here

it seems I push an object that has different data type? how to solve this?

question from:https://stackoverflow.com/questions/66062735/can-i-have-a-property-in-an-object-that-is-an-array-of-multiple-object-in-typesc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

Literals cannot be different types. Typescript infers a union type from all array elements in literal (you can see it in the error message). You can define all above options as 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...