Skip to content

Instantly share code, notes, and snippets.

@kofno
Created August 5, 2017 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kofno/b18312f428b65551e6ce6ea6592195a2 to your computer and use it in GitHub Desktop.
Save kofno/b18312f428b65551e6ce6ea6592195a2 to your computer and use it in GitHub Desktop.
leaked any example
// 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