卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章66918本站已运行427

探索 Effect-TS 中的选项 Getter

探索 effect-ts 中的选项 getter

effect-ts 提供了一组强大的工具来处理 option 类型,这些类型表示可能存在也可能不存在的值。在本文中,我们将探索使用库提供的不同 getter 获取 option 内的值的各种方法。

示例 1:使用 o.getorelse

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)
}

示例 2:使用 o.getorthrow

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
  }
}

示例 3:使用 o.getornull

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)
}

示例 4:使用 o.getorundefined

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)
}

示例 5:使用 o.getorthrowwith

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 都能正确运行。这些实用程序提供了一种清晰、类型安全的方式来处理可选值,避免了与空检查相关的常见陷阱,并增强了代码的可读性和可维护性。采用这些模式可以带来更干净、更健壮的代码库,其中

卓越飞翔博客
上一篇: 您是否尝试过 JavaScript 中的所有 API 调用?这里有一些方法可以做到这一点
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏