Adam Banko
Adam Banko

Reputation: 111

How to do type refinement of an union of two "Exact" objects?

The two possibilities of DateObj seems disjoint to me still, Flow doesn't seem to refine the type on the else branch. How can I make this correctly typed?

type DateObj = {| date: string |} | {| dateTime: string |}

export const parseDate = (dateObj: DateObj) => {
  if (dateObj.date) {
    return moment(dateObj.date).toDate()
  } else {
    return moment(dateObj.dateTime).toDate()
  }
}

Flow: property dateTime. Property not found in object type

(at the line of the last return statement)

Upvotes: 0

Views: 295

Answers (1)

Adam Banko
Adam Banko

Reputation: 111

Trying in https://flow.org/try/ helped, it gave me an additional error

if (dateObj.date) {
    ^ Sketchy null check. Perhaps you meant to check for null instead of for existence?

Fixing this error also solved my original issue

if (dateObj.date !== undefined) {

Upvotes: 2

Related Questions