facebook / facebook/flow

Disjoint Union Question

Open
#5,488 4 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

```
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?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.