How to access uncommon properties from two different object arrays that are combined into one?

Viewed 25

Consider these object Arrays in TypeScript.

const objArr1: { commonProperty: string; ABC: string }[] = [
    {
        commonProperty: "I am common",
        ABC: "I am different in object 1",
    },
    {
        commonProperty: "I am common",
        ABC: "I am different in object 1",
    },
]

const objArr2: { commonProperty: string; XYZ: string }[] = [
    {
        commonProperty: "I am common",
        XYZ: "I am different in object 2",
    },
    {
        commonProperty: "I am common",
        XYZ: "I am different in object 2",
    },
]

I am trying to access the "un-common" properties in the combined array, like so,

[...objArr1, ...objArr2].forEach(obj => {
    obj.commonProperty // No error
    obj.ABC // TypeScript gets mad
    obj.XYZ // TypeScript gets mad again
})

But it's not letting me because XYZ doesn't exist on objArr1's elements, and ABC on objArr2's elements. Can anyone suggest a workaround for this, without using type assertions or any keyword?

1 Answers

You can try something like this:

if ('ABC' in obj) obj.ABC
if ('XYZ' in obj) obj.XYZ
Related