跳至主要内容

Refine 检查器

Refine 的核心是 Checker<T> 类型。检查器本质上只是函数,它们接受一个 mixed(对于 Flow)或 unknown(对于 TypeScript)值,并返回一个 CheckResult<T>...

/**
* a function which checks if a given mixed value matches a type V,
* returning the value if it does, otherwise a failure message.
*/
type Checker<+V> = (
value: mixed,
// optional path within a parent object tree to the current value
path?: $ReadOnlyArray<string>,
) => CheckResult<V>;

/**
* the result of checking whether a type matches an expected value
*/
type CheckResult<+V> = CheckSuccess<V> | CheckFailure;

/**
* the result of failing to match a value to its expected type
*/
type CheckFailure = $ReadOnly<{
type: 'failure',
message: string,
path: $ReadOnlyArray<string>,
}>;

/**
* the result of successfully matching a value to its expected type
*/
type CheckSuccess<+V> = $ReadOnly<{
type: 'success',
value: V,
// if using `nullable()` with the `nullWithWarningWhenInvalid` option,
// failures that would have failed the check are appended as warnings
// here on the success result.
warnings: $ReadOnlyArray<CheckFailure>
}>;

下面详细介绍的内置检查器,允许轻松组合。这使得能够从基本原语构建更复杂的检查器

// type PersonType = $ReadOnly<{name: string, friends: ?Array<PersonType>}>
// const Person: Checker<PersonType>
const Person = object({
name: string(),
friends: nullable(array(lazy(() => Person)))
});

Refine 提供了一些内置检查器,有关更多信息,请参阅各个文档页面

此外,Refine 还提供了一些 实用程序函数,用于常见用例,例如 json 解析和断言函数。