When utilizing ts-results-es, I encounter an issue. This library aids in wrapping errors within a class to provide insight into potential function errors.
Here is a simplified class definition:
interface BaseResult<T, E> {}
class Err<E> implements BaseResult<never, E> {
readonly error!: E
constructor(val: E) {
this.error = val
}
}
class Ok<T> implements BaseResult<T, never> {
readonly value!: T
constructor(val: T) {
this.value = val
}
}
type Result<T, E> = Ok<T> | Err<E>
I have a function named
randomResult: () => Ok<T> | Err<U> | Err<V>
and another function that accepts a result-returning function as input function eatResultFn<T, E>(fn: () => Result<T, E>) {}
.
Sometimes, Typescript fails to identify randomResult
as () => Result<T, U | V>
and triggers an error message. This is the main problem I need to address.
To possibly resolve this issue, my initial thought was to utilize Result.mapErr()
interface BaseResult<T, E> {
mapErr<F>(mapper: (val: E) => F): Result<T, F>
}
class Err<E> implements BaseResult<never, E> {
// ...
mapErr<E2>(mapper: (err: E) => E2): Err<E2> {
return new Err(mapper(this.error))
}
}
class Ok<T> implements BaseResult<T, never> {
// ...
mapErr(_mapper: unknown): Ok<T> {
return this
}
}
This function maps errors to alternative ones. My mapping logic simply involves e => e
or more precisely
function (e: U | V) : U | V { return e }
. Nevertheless, there are instances where I continue to face errors along the lines of: Argument of type '() => Ok<T> | Err<E2> | Err<U | V>' is not assignable to parameter of type '() => Result<T, E2>'.
Why does E2
come up here? I anticipated that mapErr
would solve my dilemma.
I am open to any solutions for eliminating E2
or workarounds (besides explicitly stating the exact returned type) to help with my original issue. Your assistance is greatly appreciated.
Thank you for your support :)
Please keep in mind that the code occasionally works (refer to the Typescript Playground), another aspect that perplexes me.