flow-runtime
allows us to add runtime type-checks with a lean syntax.
For example, this:
const add = (x, y) => {
if (typeof x != 'number') {
throw new Error('x must be a number');
}
if (typeof y != 'number') {
throw new Error('y must be a number');
}
return x + y;
}
Can be written like this:
const add = (x : number, y : number) : number => {
return x + y;
}
yarn install --pure-lockfile
First add type definitions to your code. For example:
cat ./src/index.js
Build the library using Babel:
yarn build
This generates standard ES code that you can run in Node:
cat ./lib/index.js
node
> require('./lib').add(1, 2)
3
And flow-runtime
gives us type checks:
node
> require('./lib').add(1, 'world')
RuntimeTypeError: y must be a number
Expected: number
Actual Value: "world"
Actual Type: string