絞り込み
絞り込み は、Flow または TypeScript での混合/不明値の型の絞り込みとバリデータコンビネータライブラリです。
はじめに
Refine は NPM の @recoiljs/refine として公開されています。
Refine について学び始めるには、ユーティリティ と チェッカー の基本的なコンセプトに関するドキュメントを参照してください。
Refine を使いたい理由?
- コードで
unknown
TypeScript 型またはmixed
Flow 型の値に出くわし、それらの値が特定の静的型を持っていることを アサートする必要がある 場合に、Refine が役立ちます。 - Refine は、不明な値が期待される型に準拠していることを検証できる、型絞り込みヘルパー関数をビルドするための API を提供します。
- Refine は入力値を検証し、以前のバージョンからアップグレードできます。
型の絞り込み例
不明な型を、厳密に型指定された変数に強制変換します。 assertion()
は入力が予想される型と一致しない場合にスローしますが、coercion()
は null
を返します。
const myObjectChecker = object({
numberProperty: number(),
stringProperty: optional(string()),
arrayProperty: array(number()),
});
const myObjectAssertion = assertion(myObjectChecker);
const myObject: CheckerReturnType<myObjectChecker> = myObjectAssertion({
numberProperty: 123,
stringProperty: 'hello',
arrayProperty: [1, 2, 3],
});
下位互換性の例
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));
JSON パーサーの例
Refine は、厳密に型指定された組み込みパーサーを提供するために JSON
をラップします。
const myParser = jsonParser(
array(object({num: number()}))
);
const result = myParser('[{"num": 1}, {"num": 2}]');
if (result != null) {
// we can now access values in num typesafe way
assert(result[0].num === 1);
} else {
// value failed to match parser spec
}
Recoil Sync での使用
リコイルシンクライブラリはrefineを利用して、型特定、入力検証、上位互換のための型のアップグレードを行います。詳しくはrecoil-sync
のドキュメントをご覧ください。