2

我正在尝试用 rescript 模拟写入 DB 的副作用。

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

这是代码(这里是游乐场):

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

1 回答 1

3

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

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

编辑:我还要补充一点,您可能需要考虑使用更适合该范例的数据结构和 API。我可能会使用 alist并制作storagea ref<list>,但这有点取决于你还要用它做什么。

于 2021-03-30T10:52:37.147 回答