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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interestingly, the switch statement works and also detects the type error:
and changing them both to isBarking yields: