1

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?

Ken White
  • 123,280
  • 14
  • 225
  • 444
Prav
  • 610
  • 8
  • 20
  • 1
    This is the exact situation that type guards are made for. You can learn about them [here](https://www.typescriptlang.org/docs/handbook/advanced-types.html) – anut Jul 16 '22 at 03:14

1 Answers1

1

You can try something like this:

if ('ABC' in obj) obj.ABC
if ('XYZ' in obj) obj.XYZ
Telman
  • 1,444
  • 1
  • 9
  • 12