Feature Discussion: Custom `Err` types in `Result`
See original GitHub issueOriginal Comment
This function could produce an Ok.
const a = 2 as unknown as Error
const res = Err(a) // Not a string, not an Error, but TypeScript thinks so
console.log(res.isOk() // true
console.log(res.isErr() // false
Perhaps a generic isErrorLike(input: any): input is Error
function could be created which checks for characteristics of objects like Errors could be used in this function as well as the Result.isErr
function.
interface ErrorKind {
message: string;
}
type ErrorLike = Error | ErrorKind;
function isErrorLike(input: any): input is ErrorLike {
return (
input instanceof Error ||
(input &&
typeof input === 'object' &&
(Object.prototype.isPrototypeOf.call(Error, input) ||
typeof input.message === 'string'))
);
}
I am kind of concerned about forcing Error as the only type here, as then we get undefined behavior at runtime anyway… should it throw if anything not Error or string is passed?
I think Rust allows any value to be passed for E in Result<T, E>, and JS allows us to throw any value, so perhaps there could be some other signal that what’s constructed is an error?
Perhaps an optional type: 'Err' | 'Ok' = 'Ok'
as an arg, and then always pass 'Err'
from function Err
?
Such a type value could then also be used in the Result.isOk
and Result.isErr
functions to avoid prototype chain lookups which are currently used to decide Result.isErr
. Might provide a performance bump, and it’s how I do it in my private lib.
_Originally posted by @aaronhuggins in https://github.com/OliverBrotchie/optionals/pull/7#discussion_r1008324662_
Issue Analytics
- State:
- Created a year ago
- Comments:6 (3 by maintainers)
FYI, I’m a sucker for JSON serializable errors when given the chance.
I am too! 😆
This does however preclude
AmbiguousError
fromimplement
’ingError
.