Skip to content

Disjoint Union Question #5488

@maxsalven

Description

@maxsalven
type Pet = {|
  petId: string
|}

type Car = {|
  carId: string
|}

type Union = Pet | Car

This causes an error:

function getId(arg: Union): string {
  return arg.petId || arg.carId
}

This doesn't work either:

function getId(arg: Union): string {
  let id
  if (arg.petId) {
    id = arg.petId
  } else if (arg.carId) {
    id = arg.carId
  }
  return id
}

This works, but is a very convoluted amount of typing given I have told Flow that there will 100% surely be either a carId or petId attribute of type string.

function getId(arg: Union): string {
  let id
  if (arg.petId) {
    id = arg.petId
  } else if (arg.carId) {
    id = arg.carId
  } else {
    throw new Error('This is pointless')
  }
  return id
}

https://flow.org/try/#0C4TwDgpgBAChxQLxQN4B8BQUqWASQBMAuKAZ2ACcBLAOwHMM0BfDDUSKAYQEMKlVM2AMa9CJctXqMWbcNACqNKgHsa-OAjRderAGYBXGkOAq1deIQAUvOiUWmAlOMq06qLFArx9FNTYB0uIRQaFoBIhSEGDIGRiaqUOb4BNYUtlD2qk5kLvTu2AA28FBUBB5UulCpdIEWBA752CUE-AFBZdhMUBAFpNAVVeGi9Y3Ypa1p-hFRnR5ewD5qpdF6hsamiXXVdkpZzpJuKB5FCMtjldW1yQ1HTc0TNe0eXT19JRdDkSO3TePInzMoC9etAfthgAALCjKADuUBoEDhAFEKNCKJYAOQAFQhVFIJXxYGUtGARVIpAxDmec28vma0SAA

Is there a 'right way' to do this? If not, aren't these disjoint unions very limited in their ability?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions