Last active
August 9, 2017 09:47
-
-
Save deepak/ebf8f546722d82667af4c3eb57883111 to your computer and use it in GitHub Desktop.
flow-union-refinement
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 | |
// https://flow.org/en/docs/types/unions/#toc-unions-refinements | |
// flow can refine on the union. | |
// and knows when the code is operating on a number here for eg. | |
// works | |
function toStringPrimitivesGood(value: number | boolean | string): string { // Error! | |
if (typeof value === 'number') { | |
return value.toLocaleString([], { maximumSignificantDigits: 3 }); // Works! | |
} else if (typeof value === 'boolean') { | |
return String(value); | |
} else { | |
return "foo"; | |
} | |
} | |
// fails, with an abstruse error. but still! | |
function toStringPrimitivesBad(value: number | boolean | string): string { // Error! | |
if (typeof value === 'number') { | |
return String(value); | |
} else if (typeof value === 'boolean') { | |
return value.toLocaleString([], { maximumSignificantDigits: 3 }); // Works! | |
} else { | |
return "foo"; | |
} | |
} | |
toStringPrimitivesGood(12); | |
toStringPrimitivesBad(true); | |
////////////////////////////////////// | |
// Error: src/main.js:23 | |
// 23: return value.toLocaleString([], { maximumSignificantDigits: 3 }); // Works! | |
// ^^ unused function argument | |
// 56: toLocaleString(): string; | |
// ^^^^^^^^^^^^^^^^^^^^^^^^ function type expects no arguments. See lib: /private/tmp/flow/flowlib_32d44c1c/core.js:56 | |
// | |
// Error: src/main.js:23 | |
// 23: return value.toLocaleString([], { maximumSignificantDigits: 3 }); // Works! | |
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unused function argument | |
// 56: toLocaleString(): string; | |
// ^^^^^^^^^^^^^^^^^^^^^^^^ function type expects no arguments. See lib: /private/tmp/flow/flowlib_32d44c1c/core.js:56 | |
// Found 2 errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment