Babel Plugin Flow Runtime
A babel plugin which transforms Flow annotations into Type
instances available at runtime, and optionally checks values against those types.
Supports all of flow's syntax, aims for full compatibilty with flow, found a bug? Please report it.
What?
Turns code like this:
type User = id: number; name: string;;
Into code like this:
;const User = ttype'User' tobject t t;
Which you can then use like this:
User; // okUser; // throws
Installation
This plugin has a runtime dependency on flow-runtime, so make sure you install that along with this package:
npm install --save-dev babel-plugin-flow-runtimenpm install --save flow-runtime
Next, add the following to your babel configuration or .babelrc
:
Options
The plugin supports the following options:
assert
- Boolean, indicates whether types should be asserted at runtime. Defaults totrue
ifprocess.env.NODE_ENV === 'development'
, otherwisefalse
.annotate
- Boolean, indicates whether object or function values that have type annotations should be decorated with those types at runtime. Defaults totrue
.libraryName
- String, indicates which runtime to use. Defaults toflow-runtime
If assert
is true
, the following code:
const add = a: number b: number: a + b;
will be transformed into:
;const add = { let _aType = t; let _bType = t; const _returnType = t; t; t; return _returnType;};
Which is very safe, and can be very useful during development, but has a non-trivial performance overhead. It's usually a good idea to disable this feature in production.
If annotate
is true
, the following:
const add = a: number b: number: a + b;
will be transformed into:
;const add = t;
Now invoking add(x, y)
does not incur any overhead, as the parameters are not checked, but the type information is preserved and available for inspection:
console; // (a: number, b: number) => number
If both assert
and annotate
are false
then value annotations are ignored, but type aliases are still transformed:
type User = id: number; name: string;;
turns into:
;const User = ttype'User' tobject t t;
React Prop Types
When the plugin encounters a React component with a props
type annotation, the annotation is converted to react prop types:
; type Props = name: string;; Component<void Props void> { return <h1>thispropsname</h1>; }
Becomes
;; const Props = ttype'Props' tobject t; Component static propTypes = t; { return <h1>thispropsname</h1>; }