facebook / facebook/flow

Disjoint Union Question

Offen
#5,488 4 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
Rust
Sterne
22.3k
Forks
1.9k
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.