Upgrade to Pro — share decks privately, control downloads, hide ads and more …

An introduction to Flowtype

An introduction to Flowtype

An introduction to Flowtype, with examples.

C2bb0454c4af1a61e7f173d54ce17b0b?s=128

Gabriele Petronella

November 26, 2016
Tweet

Transcript

  1. an introduction to FlowType Gabriele Petronella software engineer @ buildo

    twitter: @gabro27
  2. me, hi!

  3. Software engineer at buildo

  4. None
  5. What is Flowtype?

  6. DEMO!

  7. What is Flowtype? function add(x, y) { return x +

    y; } add(2, 3); add(2, true); // oh, come on!
  8. What is Flowtype static typing? function add(x: number, y: number)

    { return x + y; } add(2, 3); // ok! add(2, true); // boolean. This type is incompatible ...
  9. Static typing

  10. SAFETY

  11. None
  12. CLARITY

  13. Clarity function addListener( event: string, listener: Function ): EventEmitter; vs

    function addListener(event, listener); // good luck
  14. Especially when /** * Adds a listener * @param {string}

    event - The event * @param {string} listener - The listener * @return {object} An EventEmitter */ function addListener(event, listener); // types, nah..
  15. but also

  16. None
  17. Static typing in JS (?!)

  18. Flowtype "vs" Typescript It's a bit like React vs Angular.

    Different scopes. Let's see what are we talking about.
  19. Flowtype "vs" Typescript (cont'd) Typescript is a language that compiles

    to JS. It has language features that are not present in JS. Examples: enums, visibility modifiers, short-hand constructors...
  20. Flowtype "vs" Typescript (cont'd) Flow is a typechecker. It doesn't

    compile to anything, it just typechecks.
  21. Flowtype + Babel ~= Typescript (or at least you can

    compare them) and actually Flowtype + Babel + Webpack ~= Typescript
  22. Flowtype "vs" Typescript (cont'd) • Typescript is a lot more

    stable • Typescript cares a lot less about soundness • Typescript's type system is less powerful • Typescript "pushes" you to its own buildchain • Type definitions are vastly more available on Typescript
  23. Flowtype, get started npm install -g flow-bin # per project

    flow init
  24. Flowtype, get started (cont'd) Add the @flow pragma to all

    the files you want Flow to consider /* @flow */ const answer = 42; // typechecks!
  25. Easy on-boarding Since you have to whitelist files, on-boarding is

    really easy. You can tinker with JS, and then progressively make your code base more solid. You have an option, which is very unobstrutive and easy to bail from.
  26. Optionality is the property of asymmetric upside with correspondingly limited

    downside — Nassim Taleb
  27. Easy on-boarding (cont'd) Flow's type inference is extremely aggressive and

    you may benefit from it even without type annotations.
  28. DEMO! Type inference

  29. Type inference // oh, I see, an array of strings

    const names = [" foo", "bar ", "baz"]; // ah no, an array of strings and numbers names.push(2); // wait, you can't trim a number! names.map(name => name.trim());
  30. Native types So, yes Flow knows about string, number and

    all the other native types you would expect. Also, it ships with typings for the JS standard library and some very common API such as the DOM, Node.js and React.
  31. Special types • mixed is supertype of all types. •

    any type can be used where a mixed is required. • any is both supertype and subtype of all the types • any type can be used where a any is required. • it can fit where anything is required
  32. DEMO! any vs mixed

  33. any vs mixed In general, prefer mixed.

  34. Composite types const user: { name: string, age: number }

    = { // |-------- the type ---------| name: 'Gabriele', age: 27 };
  35. Type aliases type User = { name: string, age: number

    }; const user: User = { name: 'Gabriele', age: 27 }; function getFriendsOf(user: User): Array<User> { ... }
  36. Quiz! const names = ['foo', 42]; What's the type of

    names?
  37. Union types const names = ['foo', 42]; So, what's the

    type of names? Answer: Array<string | number> string | number is what we call union type
  38. DEMO Dealing with union types

  39. Dealing with union types function getUser(userId: string): Error | User

    { ... } const result = getUser("foo"); if (result instanceof Error) { console.log('AAAAAHHH!'); } else { console.log(result.name); }
  40. Quiz! What's the (inferred) return type of foo? function foo(x:

    number) { if (x > 42) { return x; } }
  41. Let's try! function foo(x: number): number { if (x >

    42) { return x; } } NOPE! We return number in some cases, but in others we can return undefined.
  42. Let's try again! function foo(x: number): number | void {

    if (x > 42) { return x; } } (void is the type of undefined) YEP! That's the return type.
  43. Ok, that seems pretty common... A | void | null

    has a syntax shorthand in Flow Meet ?A the nullable type
  44. Our final attempt function foo(x: number): ?number { if (x

    > 42) { return x; } }
  45. DEMO! Dealing with nullable types

  46. Dealing with nullable types const longName = names.find(name => name.length

    > 20); if (longName) { longName.substring(0, 1); } // or if (longName != null) { longName.substring(0, 1); }
  47. Adopting Flow vademecum

  48. $FlowFixMe type User = { name: string }; // $FlowFixMe

    const u: User = { foo: 'hey' }; Disables typechecking on the next line
  49. weak mode // @flow weak less aggressive type inference, useful

    when starting on a new project.
  50. force the hand of the typecheker const x: number =

    'foo'; // sorry, nope const y: number = (('foo': any): number); // oh, ok
  51. Third-party modules You have some dependencies right? npm install -g

    flow-typed npm install --save-dev flow-bin flow-typed install It will install every compatible type definition it finds.
  52. Stripping types With Babel npm install -D babel-plugin-transform-flow-strip-types { "plugins":

    ["transform-flow-strip-types"] } With flow-remove-types npm install -g flow-remove-types flow-remove-types src/ --out-dir lib/ flow-node index.js # or run directly
  53. A wild demo appears!

  54. Useful resources • https:/ /flowtype.org/docs/ • https:/ /flowtype.org/try/ • Jeff

    Morrison - A Deepdive into Flow https:/ /www.youtube.com/ watch?v=VEaDsKyDxkY • https:/ /medium.com/@gcanti
  55. Wrap up • a typechecker, not a language • powerful

    type system • easy to adopt, easy to leave
  56. THANK YOU! Questions? function speaker(question): ?answer { // TODO }

    Twitter: @gabro27