跳到主要內容

Refine 0.1

·閱讀時間 2 分鐘

@recoiljs/refine 函式庫已經有最初的開源版本,提供 Flow 和 TypeScript 的類型精煉和輸入驗證!若要開始學習 Refine,請查閱 工具程式檢查器 的核心概念文件。

recoil-sync 函式庫利用 Refine 進行類型精煉、輸入驗證以及升級類型以維持向下相容性。請參閱 recoil-sync 文件 以取得更多詳細資料。

我為什麼需要使用 Refine?

  • 當您的程式碼遇到未知的 TypeScript 類型或混合 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
}