mobily / ts-belt

🔧 Fast, modern, and practical utility library for FP in TypeScript.
https://mobily.github.io/ts-belt
MIT License
1.1k stars 30 forks source link

F.when/unless different return type to input type? #30

Closed Darkle closed 2 years ago

Darkle commented 2 years ago

Hi, I have a use case where I would like to use F.when, but have the return type be different to the type going in to the function. At the moment the return type for F.when and F.unless can only be the input type.

The context here is creating a document in a mongodb database and first checking to see if the document already exists. If it exists (checked via MyModel.exists()), a document object is returned, if it doesnt exist, null is returned.

So I would like to do something like this:

MyModel.exists({foo:'bar'})
  .then(O.fromNullable)
  .then(F.when(O.isNone, () => MyModel.create({foo:'bar'})))
mobily commented 2 years ago

@Darkle hm, in this specific case, I'd use a different approach:

MyModel.exists({foo:'bar'})
  .then(O.fromNullable)
  .then(O.map(() => MyModel.create({foo:'bar'}))
  .then(O.toUndefined)

// or

MyModel.exists({foo:'bar'})
  .then(
    flow(
      O.fromNullable,
      O.map(() => MyModel.create({foo:'bar'}),
      O.toUndefined,
    )
  )

in terms of F.when and F.unless usage, both TS signatures have been updated in v3.12.0, and now it's possible to return a different type