Flow Runtime
A runtime type system for JavaScript with full Flow compatibility.
What?
Provides 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.
See the docs for more information.
Usage
import t from 'flow-runtime';
const number = t.number();
const string = t.string();
string.accepts('foo');
string.accepts(123);
number.accepts(123);
string.assert('Hello World!');
string.assert(false);
number.assert(456);
number.assert('nope');
const numberOrString = t.union(number, string);
numberOrString.assert(123);
numberOrString.assert("baz");
numberOrString.assert(false);
const fooOrBar = t.union(
t.string('foo'),
t.string('bar')
);
fooOrBar.assert('foo');
fooOrBar.assert('bar');
fooOrBar.assert('qux');
const Thing = t.object(
t.property('name', t.string()),
t.property('url', t.nullable(t.string()))
);
Thing.assert({
name: 'Example',
url: 'http://example.com/'
});
Thing.assert({
name: 'Example'
});
Thing.assert({
name: false
});
const arrayOfStrings = t.array(t.string());
arrayOfStrings.assert()
const UserStatus = t.union(
t.string('PENDING'),
t.string('ACTIVE'),
t.string('INACTIVE')
);
const PreferenceName = t.union(
t.string('marketingOptIn'),
t.string('darkColourScheme')
);
const UserPreferences = t.object(
t.indexer(PreferenceName, t.boolean())
);
const User = t.object({
id: t.number(),
name: t.string(),
email: t.string(),
status: UserStatus,
preferences: UserPreferences
});
const validUser = {
id: 123,
name: 'Sally',
email: 'sally@example.com',
status: 'PENDING',
preferences: {
marketingOptIn: true
}
};
const invalidUser = {
id: false,
name: 'Bob',
email: 'bob@example.com',
status: 'NOPE',
preferences: {
marketingOptIn: true,
nope: true
}
};
User.accepts(validUser);
User.accepts(invalidUser);
User.assert(validUser);
User.assert(invalidUser);