Disjoint Union Question
- Lingua principale
- Rust
- Stelle
- 22.3k
- Fork
- 1.9k
- Metriche di merge delle PR
- Nessuna PR unita negli ultimi 30g
Descrizione
```
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?
Guida per i contributori
Apri la guida per i contributori
Valutazione
Questa issue non è ancora stata valutata.