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中文网其他相关文章!