跳到主要內容

精緻化

Refine 是一種類型精緻化和驗證組合器函式庫,適用於 Flow 或 TypeScript 中的混合/未知值。

入門

Refine 已發布為 @recoiljs/refine,在 NPM 上發布。

若要開始瞭解 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 同步中使用

Recoil Sync 程式庫為型別優化、輸入驗證,以及為向下相容升級型別而運用 Refine。詳情請參閱 recoil-sync 文件