Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...