Skip to content

H:3. Type Checking

Cody Brunner edited this page Mar 13, 2017 · 4 revisions

Type-checking is a nice way to catch errors while in development by strictly enforcing what to expect a variable or argument to be. A quick example:

// The name of our function makes it pretty obvious we want to sum two variables
// you'd kinda figure numbers right?
const sum = (a, b) => a + b;
// but that is not implicitly known so even though you and I know that the following
// would fail the Javascript Engine doesn't know that:
sum('hello', 2); 
// JS Engine screams at you...but this comes after the code has attempted to run.
// With type-checking we can say (using flow-syntax for example):
const sum = (a: number, b: number): number => a + b;
// We are expecting both params to be of type number and the return as well.
// Now if in our code we mistakenly write:
sum('hello', 2); 
// Flow Error: Expected argument to be a number.

I will be using flow from Facebook. If you want to know more about flow visit Flow; or if you want to use another type-script packages: Typescript & there are other's I'm sure.

Yellow-Stone:picnic-basket-generator yogibear$ flow init ### must install flow-bin globally to run this in CLI.
### generates a .flowconfig
Yellow-Stone:picnic-basket-generator yogibear$ npm i -D flow-bin flow-typed eslint-plugin-flowtype

First let's update the .eslintrc

{
  "extends": "equimper",
  "plugins": ["flowtype"]
}

.flowconfig

[ignore]
.*/node_modules/.*
.*/flow-typed/.*
.*/coverage/.*
[include]

[libs]

[options]