Created
February 22, 2018 15:56
-
-
Save richardbarrell-calvium/fb5ba5e68a556979f50e12b7c685c83f to your computer and use it in GitHub Desktop.
Spread operator in flow - works better with $Exact<T> or with exact types
This file contains 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 | |
type HaveHeyType = { | |
hey: number, | |
}; | |
type HaveBeeType = { | |
bee: string, | |
}; | |
type SpreadIsUselessType = { | |
...HaveHeyType, | |
...HaveBeeType, | |
}; | |
type ExactSpreadWorksGreatType = { | |
...$Exact<HaveHeyType>, | |
...$Exact<HaveBeeType>, | |
}; | |
const c: SpreadIsUselessType = { | |
hey: 1, | |
bee: 'honey gatherer', | |
}; | |
// No fail, even though it is missing 'bee'. | |
const cBad1: SpreadIsUselessType = { | |
hey: 1, | |
}; | |
// No fail, even though it is missing 'hey'. | |
const cBad2: SpreadIsUselessType = { | |
bee: 'honey gatherer', | |
}; | |
// No fail, even though it has values with the wrong types for 'hey' and 'bee'! | |
const cBad3: SpreadIsUselessType = { | |
hey: 'bad', | |
bee: 999, | |
}; | |
const d: ExactSpreadWorksGreatType = { | |
hey: 3, | |
bee: 'technically bees gather *nectar* and make honey. they do not gather honey directly', | |
} | |
// Uncomment to get an error because 'bee' is missing. | |
/* | |
const dBad1: ExactSpreadWorksGreatType = { | |
hey: 3, | |
}; | |
*/ | |
// Uncomment to get an error because 'hey' is missing. | |
/* | |
const dBad2: ExactSpreadWorksGreatType = { | |
bee: 'bumble', | |
}; | |
*/ | |
// Uncomment to get an error because 'hey' and 'bee' have values with wrong types | |
/* | |
const dBad3: ExactSpreadWorksGreatType = { | |
hey: 'bad', | |
bee: 999, | |
}; | |
*/ | |
type ExactlySeaType = {| | |
sea: Object, | |
|}; | |
type ExactlyOtterType = {| | |
otter: string, | |
|}; | |
const aSea: ExactlySeaType = {sea: {}}; | |
const anOtter = {otter: 'mitch'}; | |
type SeaOtterType = { | |
...ExactlySeaType, | |
...ExactlyOtterType, | |
}; | |
const aBoth: SeaOtterType = { | |
sea: {}, | |
otter: 'wet', | |
}; | |
// Uncomment to get an error because 'sea' and 'otter' have values with wrong types | |
/* | |
const badBoth: SeaOtterType = { | |
sea: 'wrong', | |
otter: {}, | |
}; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment