Refine 工具
除了 Refine 提供的核心 检查器 组合器之外,库还公开了某些实用函数,以帮助处理 JSON 解析和断言函数等事项。
coercion()
轻松创建用于空值强制转换值的函数(带有可选检查结果回调)
let callbackResult: ?CheckResult<Date> = null;
// optional callback
const onResult = (result: CheckResult<Date>) => {
callbackResult = result;
};
// mixed => ?Date
const coerce = coercion(date(), onResult);
const d = new Date();
assert(coerce(d) === d, 'should resolve to value');
assert(callbackResult != null, 'should be set');
assert(callbackResult.type == 'success', 'should succeed');
assertion()
轻松从您的检查器函数创建断言函数。
// mixed => $ReadOnlyArray<number>;
const assertArrayOfNum = assertion(array(number()));
declare value: mixed;
try {
const myArray: $ReadOnlyArray<number> = assertArrayOfNum(value);
} catch {
// assertion error if value is invalid
}
CheckerReturnType<Checker>
要从检查器函数中提取底层类型,可以使用 CheckerReturnType<typeof checker>
…
const check = array(number());
// $ReadOnlyArray<number>;
type MyArray = CheckerReturnType<typeof check>;
jsonParser()
/ jsonParserEnforced()
轻松从您的检查器函数创建 JSON 解析器。
// ?string => ?$ReadOnlyArray<number>;
const parse = jsonParser(array(number()));
const result = parse('[1,2,3]']);
如果您想在无效/空 JSON 上抛出错误,可以使用 jsonParserEnforced()
// creates a json parser which will throw on invalid values
const parse = jsonParserEnforced(
object({a: string(), b: nullable(number()), c: bool()}),
// message to append to error message
'Configuration is invalid'
);
const result = parse('...');
// at this point, result must be correct, or `parse()` would throw...
result.a.includes(...);