Effect-TS 提供了一組強大的工具來處理 Option 類型,這些選項表示可能存在或不存在的值。在本文中,我們將探索使用函式庫提供的不同 getter 來取得 Option 內的值的各種方法。
O.getOrElse 函數可讓您在 Option 為 None 時提供預設值。當您想要確保後備值始終可用時,這非常有用。
import { Option as O, pipe } from 'effect'; function getters_ex01() { const some = O.some(1); // Create an Option containing the value 1 const none = O.none(); // Create an Option representing no value console.log(pipe(some, O.getOrElse(() => 'none'))); // Output: 1 (since some contains 1) console.log(pipe(none, O.getOrElse(() => 'none'))); // Output: 'none' (since none is None) }
O.getOrThrow 函數如果是 Some,則傳回 Option 內的值,否則拋出預設錯誤。
import { Option as O, pipe } from 'effect'; function getters_ex02() { const some = O.some(1); // Create an Option containing the value 1 const none = O.none(); // Create an Option representing no value console.log(pipe(some, O.getOrThrow)); // Output: 1 (since some contains 1) try { console.log(pipe(none, O.getOrThrow)); // This will throw an error } catch (e) { console.log(e.message); // Output: getOrThrow called on a None } }
O.getOrNull 函數如果是 Some,則傳回 Option 內部的值,否則傳回 null。
import { Option as O, pipe } from 'effect'; function getters_ex03() { const some = O.some(1); // Create an Option containing the value 1 const none = O.none(); // Create an Option representing no value console.log(pipe(some, O.getOrNull)); // Output: 1 (since some contains 1) console.log(pipe(none, O.getOrNull)); // Output: null (since none is None) }
O.getOrUndefine 函數如果是 Some,則傳回 Option 內部的值,否則傳回 undefined。
import { Option as O, pipe } from 'effect'; function getters_ex04() { const some = O.some(1); // Create an Option containing the value 1 const none = O.none(); // Create an Option representing no value console.log(pipe(some, O.getOrUndefined)); // Output: 1 (since some contains 1) console.log(pipe(none, O.getOrUndefined)); // Output: undefined (since none is None) }
import { Option as O, pipe } from 'effect'; function getters_ex05() { const some = O.some(1); // Create an Option containing the value 1 const none = O.none(); // Create an Option representing no value console.log(pipe(some, O.getOrThrowWith(() => new Error('Custom Error')))); // Output: 1 (since some contains 1) try { console.log(pipe(none, O.getOrThrowWith(() => new Error('Custom Error')))); // This will throw a custom error } catch (e) { console.log(e.message); // Output: Custom Error } }
透過使用這些不同的 getter,您可以有效地處理各種場景中的 Option 類型,確保您的程式碼無論 Option 是 Some 還是 None 都能正確運作。這些實用程式提供了一種清晰、類型安全的方式來處理可選值,避免了與空檢查相關的常見陷阱,並增強了程式碼的可讀性和可維護性。採用這些模式可以帶來更乾淨、更健壯的程式碼庫,其中
以上是探索 Effect-TS 中的選項 Getter的詳細內容。更多資訊請關注PHP中文網其他相關文章!