高度な Refine チェッカー
コレクションとプリミティブに加えて、以下の組み合わせチェッカーを使用してより複雑なタイプをモデル化できます。
or()
2 つの指定チェッカーのうち 1 つとして値を検証します。
// define checker
const check = or(number(), array(string()));
// result type is correct
const value: number | $ReadOnlyArray<string> = check(1);
// test a value
assert(check(1).type === 'success');
assert(check(['one']).type === 'success');
assert(check(true).type === 'failure');
union()
or()
の一般化バージョンであり、複数の値に使用できます(注: 現在、フローにはunion
の明示的な型パラメーターが必要という制限があり、したがって別のor()
が必要になっています)。
// define checker
const check = union(number(), array(string()), bool());
// test a value
assert(check(1).type === 'success');
assert(check(['one']).type === 'success');
assert(check(true).type === 'success');
assert(check([1]).type === 'failure');
lazy()
: 再帰的コレクション
lazy()
ユーティリティを使用すると、再帰的チェッカーを定義できます。
const Person = object({
name: string(),
friends: nullable(array(lazy(() => Person))),
});
const result = Person({name: 'alice', friends: [{name: 'bob'}]});
// should succeed to validate
assert(result.type === 'success');
警告: チェッカーがスタックオーバーフローするため、値内の再帰参照は機能しません。
const Person = object({
name: string(),
friends: nullable(array(lazy(() => Person))),
});
const alice = {name: 'alice', friends: []};
// add self to own friends
alice.friends.push(alice);
// Error: will stack overflow
Person(alice);
カスタムタイプ
custom()
custom
ユーティリティを使用すると、クラスなどの簡単なカスタムタイプを簡単に定義できます。
警告: 型パラメーター(MyClass<T>
など)を必要とするクラスと共にこれを使用しないでください。instanceof
を使用して型パラメーターが正しいことを検証する方法がないためです。
class MyClass {}
function myClass(): Checker<MyClass> {
return custom(
value => value instanceof MyClass ? value : null,
'value is not a valid instance of MyClass'
);
}
const check = array(myClass());
assert(check([new MyClass()]).type === 'success');
assert(check([3]).type === 'failure');
asType()
asType()
は 1 つのタイプから別のタイプに変換します。予測されるタイプのチェッカーと、別の出力タイプに変換するためのコールバック関数を指定します。たとえば、この機能を使用して、値を不透明なタイプに強制変換できます。
opaque type ID = string;
const IDChecker: Checker<ID> = asType(string(), s => (s: ID));
match()
このチェッカーはunion
の別名であり、すべての入力チェッカーは同じ出力タイプを生成するように制限されています。
match()
とasType()
を使用すると、以前のタイプから最新バージョンにアップグレードできます。
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));
constraint()
値が論理述語に合格する必要がある場合は、constraint()
を使用できます。
const evenNumber = constraint(
number(),
n => n % 2 === 0
);
const passes = evenNumber(2);
// passes.type === 'success';
const fails = evenNumber(1);
// fails.type === 'failure';
withDefault()
指定値がnullの場合にwithDefault()
値を提供するチェッカーです。
const objPropertyWithDefault = object({
foo: withDefault(number(), 123),
});
// result will be `{foo: 123}`.
const result = check({});