UNPKG

2.38 kBMarkdownView Raw
1# Flow Runtime
2
3A runtime type system for JavaScript with full [Flow](https://flowtype.org/) compatibility.
4
5
6## What?
7
8Provides a rich API for defining, inspecting and verifying data types in JavaScript. Any value that can be represented in JS can be represented by `flow-runtime`, including full support for polymorphism and parameterized types.
9
10
11[See the docs for more information](https://codemix.github.io/flow-runtime/#/docs).
12
13## Usage
14
15```js
16import t from 'flow-runtime';
17
18const number = t.number();
19const string = t.string();
20
21string.accepts('foo'); // true
22string.accepts(123); // false
23number.accepts(123); // true
24
25string.assert('Hello World!'); // ok
26string.assert(false); // throws
27number.assert(456); // ok
28number.assert('nope'); // throws
29
30const numberOrString = t.union(number, string);
31
32numberOrString.assert(123); // ok
33numberOrString.assert("baz"); // ok
34numberOrString.assert(false); // throws
35
36const fooOrBar = t.union(
37 t.string('foo'),
38 t.string('bar')
39);
40
41fooOrBar.assert('foo'); // ok
42fooOrBar.assert('bar'); // ok
43fooOrBar.assert('qux'); // throws
44
45const Thing = t.object(
46 t.property('name', t.string()),
47 t.property('url', t.nullable(t.string()))
48);
49
50Thing.assert({
51 name: 'Example',
52 url: 'http://example.com/'
53}); // OK
54
55
56Thing.assert({
57 name: 'Example'
58}); // OK
59
60Thing.assert({
61 name: false
62}); // throws
63
64const arrayOfStrings = t.array(t.string());
65
66arrayOfStrings.assert()
67
68// ---------------------------------------------
69
70const UserStatus = t.union(
71 t.string('PENDING'),
72 t.string('ACTIVE'),
73 t.string('INACTIVE')
74);
75
76const PreferenceName = t.union(
77 t.string('marketingOptIn'),
78 t.string('darkColourScheme')
79);
80
81const UserPreferences = t.object(
82 t.indexer(PreferenceName, t.boolean())
83);
84
85const User = t.object({
86 id: t.number(),
87 name: t.string(),
88 email: t.string(),
89 status: UserStatus,
90 preferences: UserPreferences
91});
92
93const validUser = {
94 id: 123,
95 name: 'Sally',
96 email: 'sally@example.com',
97 status: 'PENDING',
98 preferences: {
99 marketingOptIn: true
100 }
101};
102
103const invalidUser = {
104 id: false, // invalid
105 name: 'Bob',
106 email: 'bob@example.com',
107 status: 'NOPE', // invalid
108 preferences: {
109 marketingOptIn: true,
110 nope: true // invalid
111 }
112};
113
114User.accepts(validUser); // true
115User.accepts(invalidUser); // false
116
117User.assert(validUser); // OK
118User.assert(invalidUser); // throws TypeError
119
120```
\No newline at end of file