Created
August 5, 2017 14:57
-
-
Save kofno/b18312f428b65551e6ce6ea6592195a2 to your computer and use it in GitHub Desktop.
leaked any example
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
// From the flow docs: https://flow.org/en/docs/types/any/#toc-avoid-leaking-any | |
// @flow | |
function fn(obj: any) /* (:any) */ { | |
let foo /* (:any) */ = obj.foo; | |
let bar /* (:any) */ = foo * 2; | |
return bar; | |
} | |
// returns an any type (implicitly) | |
// Leaks any types into your code | |
let bar /* (:any) */ = fn({ foo: 2 }); | |
let baz /* (:any) */ = "baz:" + bar; | |
// The solution is to explicitly type something | |
// @flow | |
function fn(obj: any) /* (:number) */ { | |
let foo: number = obj.foo; // <-- here | |
let bar /* (:number) */ = foo * 2; | |
return bar; | |
} | |
// Now we return a number (implicitly) | |
// So what if there was a switch that made the first example a compiler error? | |
// Then, if you _meant_ to return any, you'd have to be explicit | |
// @flow | |
function fn(obj: any): any { | |
let foo /* (:any) */ = obj.foo; | |
let bar /* (:any) */ = foo * 2; | |
return bar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment