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

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

can I have a property in an object that is an array of multiple object in typescript?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...