typescript - 使用 Option 代替 typescript 的可选 `?` 运算符有什么好处?

标签 typescript functional-programming option-type fp-ts

我正在开始使用 fp-ts lib,并且想知道使用 Option 类型相对于 typescript 由问号 ? 运算符表示的可选值的默认概念有什么优势?

最佳答案

Typescript 用问号告诉你是否有值。然而,通常您会想要对它们执行某种计算,这就是 fp-ts 中的 Option 类型大放异彩的时候。

例如,假设我们在商店里有两种商品,它们可以选择有价格,我们想编写一个函数来获取它们的价格,否则我们返回一些表示“非卖品”的值。首先我们将看看如何在普通 typescript 中做到这一点

type ShopItem = {
    price?:number
}
const getPrice = (item1: ShopItem, item2: ShopItem):number | null => {
    const price1 = item1.price;
    const price2 = item2.price;

    if (price1 && price2) {
        return price1 + price2;
    }
    return null;
}

这有一些问题。首先,其中存在一个错误,因为如果价格为 0,则该商品应该出售,但我们的错误检查会短路并返回 null。其次,它的扩展性不太好。如果我们想要添加多个 ShopItems 甚至其他类型的具有可选值的商品,我们需要不断检查这些值是否为 null。

现在让我们将其与 fp-ts 示例进行比较 https://codesandbox.io/s/laughing-wu-pffe3

import { some, none, ap, Option } from "fp-ts/lib/Option";
import { pipe } from 'fp-ts/lib/pipeable'

type ShopItem = {
    price:Option<number> //this type will either be a Some<number> or None
}
const getPrice = (item1: ShopItem, item2: ShopItem): Option<number> =>
  pipe( 
   some((a:number) => (b:number) => a + b), 
   ap(item1.price),
   ap(item2.price)
  );

其工作方式是,我们获取 item1 价格和 item2 价格,并将其输入到 some 内的加法函数中。请注意,没有任何空检查,因为它已被抽象为我们的 None 类型。

关于typescript - 使用 Option 代替 typescript 的可选 `?` 运算符有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60886273/

相关文章:

c# - ASP .Net Core Dto 和 Controller 到 typescript 类和接口(interface)

angular - 如何使用 ng bootstrap 和 angular 6 以编程方式设置自定义日期?

angular - "ng lint"安静选项?

java - 我将如何组合 BiPredicate 和 Predicate?

haskell - 在 Haskell 中,如何自动派生这样一个自定义类?

swift - 我试图理解 Swift 中的 Optionals。代码有效,但我不明白为什么

java - JAVA 8 中的 NULL 安全对象检查

typescript - 为什么我不能使用常量中的值作为自定义类型定义?

Scala-惯用方式来计算交错数组的总和?

swift - swift 中的可选 if 语句在幕后发生了什么