メインコンテンツへスキップ

Refine 0.1

·2分間読む

@recoiljs/refineライブラリの最初のオープンソースリリースをご紹介します。これは、FlowとTypeScriptの型の絞り込みと入力の検証に役立ちます。リファインについて学習するには、ユーティリティーチェッカーの中核概念に関するドキュメントを参照してください。

Recoil Syncライブラリは、リファインを活用して型の絞り込み、入力の検証、および後方互換性のための型のアップグレードを行います。recoil-syncドキュメントで、詳細を参照してください。

なぜリファインを使う必要があるの?

型の絞り込みの例

未知の型を強く型付けされた変数に強制的に変換します。 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
}