Skip to main content

Refine

Refine is a type-refinement and validator combinator library for mixed / unknown values in Flow or TypeScript.

Getting Started​

Refine is published as @recoiljs/refine on NPM.

To get started learning about Refine, check out the documentation on the core concepts of Utilities and Checkers.

Why would I want to use Refine?​

Type Refinement Example​

Coerce unknown types to a strongly typed variable. assertion() will throw if the input doesn't match the expected type while coercion() will return null.

const myObjectChecker = object({
numberProperty: number(),
stringProperty: optional(string()),
arrayProperty: array(number()),
});

const myObjectAssertion = assertion(myObjectChecker);
const myObject: CheckerReturnType<myObjectChecker> = myObjectAssertion({
numberProperty: 123,
stringProperty: 'hello',
arrayProperty: [1, 2, 3],
});

Backward Compatible Example​

Using match() and asType() you can upgrade from previous types to the latest version.

const myChecker: Checker<{str: string}> = match(
object({str: string()}),
asType(string(), str => ({str: str})),
asType(number(), num => ({str: String(num)})),
);

const obj1: {str: string} = coercion(myChecker({str: 'hello'}));
const obj2: {str: string} = coercion(myChecker('hello'));
const obj3: {str: string} = coercion(myChecker(123));

JSON Parser Example​

Refine wraps JSON to provide a built-in strongly typed parser.

const myParser = jsonParser(
array(object({num: number()}))
);

const result = myParser('[{"num": 1}, {"num": 2}]');

if (result != null) {
// we can now access values in num typesafe way
assert(result[0].num === 1);
} else {
// value failed to match parser spec
}

Usage in Recoil Sync​

The Recoil Sync library leverages Refine for type refinement, input validation, and upgrading types for backward compatibility. See the recoil-sync docs for more details.