gigobyte / purify

Functional programming library for TypeScript - https://gigobyte.github.io/purify/
ISC License
1.5k stars 57 forks source link

Additional types #713

Open probablykabari opened 3 days ago

probablykabari commented 3 days ago

I've found myself using these types often when abstracting the use of Either and EitherAsync:

type ExtractRight<E> = E extends EitherAsync<unknown, infer R> ? R : E extends PromiseLike<Either<unknown, infer R>> ? R : never
type ExtractLeft<E> = E extends EitherAsync<infer L, unknown> ? L : E extends PromiseLike<Either<infer L, unknown>> ? L : never

For example

function getUser() {
 return EitherAsync(...data or some failure...)
}

type User = ExtractRight<ReturnType<typeof getUser>>
function doSomethingWithUser(user: User) { ... }

EitherAsync(async ({ fromPromise }) => {
  const user = await fromPromise(getUser())
  // this line is hard to do if you aren't strongly typing every single function return
  const otherStuff = await fromPromise(doSomethingWithUser(user))
})

I can make a PR to add them if that's cool. Not sure if anyone else really encounters this.

gigobyte commented 5 hours ago

Looks interesting and useful, I think those types are a good fit for the library, but there's no need for a PR, I'll add them in the next release.