Typescript property does not exist on union type

You have to narrow down the type. You can do so by using the in operator.

const getText = (obj: Obj1 | Obj2): string => {
  if ("message" in obj) {
    return obj.message
  }

  return obj.text
}

Leave a Comment