Last active
August 16, 2016 13:12
-
-
Save kevinrobinson/37b09ba96f662a5500b68588fc6634f0 to your computer and use it in GitHub Desktop.
Trying to use disjoint unions in Flow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @flow */ | |
// Modeled after https://github.com/facebook/flow/issues/1664#issuecomment-222934455 | |
type AnimalT = { | |
id: number, | |
name: string | |
}; | |
type CatT = AnimalT & { | |
isPurring: bool | |
}; | |
type DogT = AnimalT & { | |
isBarking: bool | |
}; | |
// This is cool. | |
const garfield:AnimalT = { | |
id: 42, | |
name: 'Garfield', | |
isPurring: true | |
}; | |
console.log(garfield); | |
// This is cool. | |
const rex:DogT = { | |
id: 45, | |
name: 'Rex', | |
isBarking: false | |
}; | |
console.log(rex); | |
// Trying to check for a property and then work with a more | |
// specific type doesn't seem to work. | |
if (garfield.isPurring) { | |
const cat:CatT = garfield; | |
console.log(cat); | |
} | |
// Nor does the approach in https://github.com/facebook/flow/issues/1664#issuecomment-222934455 | |
if (garfield.isPurring) { | |
(garfield:CatT); | |
console.log(garfield); | |
} |
Interestingly, the switch statement works and also detects the type error:
switch (garfield.type) {
case 'cat': console.log(garfield.isPurring); break;
case 'dog': console.log(garfield.isBarking); break;
}
and changing them both to isBarking yields:
51: case 'cat': console.log(garfield.isBarking); break;
^^^^^^^^^ property `isBarking`. Property not found in
51: case 'cat': console.log(garfield.isBarking); break;
^^^^^^^^ object type
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also tried adding in an explicit sentinel value (versus matching on the fields that are present). I was trying to match the approach in the docs here: https://flowtype.org/docs/disjoint-unions.html
This didn't work either, and my read of the error message is that even expressing the disjoint union was a problem (before even getting to checking the real code)
Code:
This led to these errors: