跳至主要內容

Refinement 實用程式

除了 檢查器組合器,Refinement 也提供了實用函數來協助處理 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(...);