精緻檢查器
Refine 的核心是 Checker<T>
類型。檢查器基本上就是函式,可接收一個 混合
(對於 Flow) 或 未知
(對於 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 解析和驗證函式。