如何强制函数在 Rescript 中返回“单位”?

时间:2021-03-30 10:35:58

标签: rescript

我试图模拟用 rescript 写入数据库的副作用。

所以我想在调用 repository.add 时将数据推送到数组中。 Js.Array.push 返回一个 int,我不关心。我想强制返回 unit,以便我的签名显示 unit,这让我立即知道此函数会产生副作用。

这是代码 (and a playground here):

module Person = {
  type entity = {
    firstName: string
  }
  
  type repository = {
    add: entity => unit,
    getAll: unit => array<entity>
  }

  
  let createRepository = (): repository => {
    let storage: array<entity> = []
    
    {
        add: entity => {
          Js.Array.push(entity, storage)  // This has type: int -> Somewhere wanted: unit
          ()         // how to force to return 'unit' there ?
       },
        getAll: () => storage
    }
  }
}

1 个答案:

答案 0 :(得分:2)

如果您像您一样返回 unit,函数将返回 ()。这不是真正的问题。编译器抱怨的原因是您隐式忽略了 Js.Array.push 返回的值,这通常是一个错误。您可以通过显式忽略它来关闭编译器:

let _: int = Js.Array.push(entity, storage)

编辑:我还要补充一点,您可能需要考虑使用更适合范式的数据结构和 API。我可能会使用 list 并将 storage 改为 ref<list>,但这在一定程度上取决于您打算用它做什么。