Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Last active February 9, 2025 23:17
Show Gist options
  • Save subtleGradient/e7cef476dee252c1529903cd2487f441 to your computer and use it in GitHub Desktop.
Save subtleGradient/e7cef476dee252c1529903cd2487f441 to your computer and use it in GitHub Desktop.
/*
https://gist.github.com/subtleGradient/e7cef476dee252c1529903cd2487f441
MooTools gang ✊
shamelessly stolen from Daniel Steigerwald's Evolu
then modified / extended by Tom Aylott
https://github.com/evoluhq/evolu-private/blob/main/packages/common/src/Result.ts
*/ /*
The MIT License (MIT)
Copyright (c) 2023–2025 Evolu
Copyright (c) 2025 Tom Aylott
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const THROW = Symbol.for('THROW') as never
export type ResultValue<T, E = never> = T extends Ok<infer T> ? T : E
export const ResultValue = <T, E = never>(result: Result<T, any>, fallback: E = THROW): T | E => {
if (result.ok) return result.value
if (fallback === THROW) throw result.error
return fallback
}
export type ResultError<E, T = never> = E extends Err<infer E> ? E : T
export const ResultError = <E, T = never>(result: Result<any, E>, fallback: T = THROW): E | T => {
if (!result.ok) return result.error
if (fallback === THROW) {
const [name, reason, cause] = ['FallbackResultError' as const, result.value, result]
throw Object.assign(new Error(`expected an error result, got ${reason}`, {cause}), {name, reason})
}
return fallback
}
export type Ok<T> = {readonly ok: true; readonly value: T}
export type Err<E> = {readonly ok: false; readonly error: E}
export const ok = <T>(value: T): Ok<T> => ({ok: true, value})
export const err = <E>(error: E): Err<E> => ({ok: false, error})
type AnyOk<T> = T extends Ok<unknown> ? T : Ok<T>
type AnyErr<E> = E extends Err<unknown> ? E : Err<E>
export function Ok<T>(it: T | Ok<T>): Ok<T> {
if (isResult(it) && it.ok) return it
return ok(it)
}
export function Err<E>(cause: E | Err<E>): Err<E> | Err<Errorish<'OkError'>> {
if (isErrorish(cause)) return err(cause) // early return since some errorish things quack like results
if (isResult(cause)) return !cause.ok ? cause : err({...OkError, cause})
return err(cause)
}
type falsey = false | null | undefined | 0 | '' | 0n | []
export type Result<T, E> = Ok<T> | Err<E>
export function Result<T extends null, E = never>(): Ok<T>
export function Result<T, E>(error: E): E extends falsey ? Ok<T> & {error: E} : Err<E>
export function Result<T, E>(error: E, value: T): E extends falsey ? Ok<T> & {error: E} : Err<E> & {value: T}
export function Result<T, E>(...args: [] | [error: E] | [error: E, value: T]) {
if (args.length === 0) return ok(null as T)
const [error] = args
if (args.length === 1) return err(error)
const [, value] = args
return {ok: !error, error, value}
}
Result.is = isResult
function isResult<T, E>(it: unknown): it is Result<T, E> {
return isAnyObject(it) && 'ok' in it && (typeof it.ok === 'boolean' && it.ok ? 'value' in it : 'error' in it)
}
type AnyObject = Record<keyof any, unknown>
const isAnyObject = (it: unknown): it is AnyObject => typeof it === 'object' && it !== null
const stringEndsWith = <Name extends string>(name: Name, it: string): it is `${string}${Name}` => it.endsWith(name)
const stringEndsWithError = (name: string): name is AnyErrorName => stringEndsWith('Error', name)
const nameEndsWith = <Name extends AnyErrorName>(name: Name, it: object): it is {name: `${string}${Name}`} =>
'name' in it && typeof it.name === 'string' && stringEndsWith(name, it.name)
const hasStringProp = <K extends string>(it: Record<keyof any, unknown>, key: K): it is {[K in typeof key]: string} =>
key in it && typeof it[key] === 'string'
export type Errorish<N extends AnyErrorName = any, M extends string = any> =
| (Error & {name: N; message: M})
| {name: N; message: M}
type AnyErrorName = `${string}Error`
export function Errorish(): null
export function Errorish(no: falsey): null
export function Errorish<E extends Errorish>(error: E): E
export function Errorish<C>(cause: C): C extends falsey ? never : Errorish<'UnknownError'> & {cause: C}
export function Errorish<N extends AnyErrorName, M extends string, X extends object>(
name: N,
mess?: M,
xtra?: X,
): Errorish<N, M> & X
export function Errorish<M extends string, X extends object>(mess: M, xtra?: X): Errorish<'UnknownError', M> & X
export function Errorish<N extends AnyErrorName, M extends string, X extends object>(...args: unknown[]) {
if (isFalsey(args[0])) return null
if (isErrorish(args[0])) return args[0]
if (typeof args[0] === 'string' && stringEndsWithError(args[0])) {
const [name, message, xtra = AnyError] = args
return Object.assign(new Error(String(message)), xtra, {name})
}
const [cause, xtra = AnyError] = args
return Object.assign(new Error(String(cause)), UnknownError, isAnyObject(xtra) ? xtra : {}, {cause})
}
const OkError = {name: 'OkError', message: 'unexpectedly ok'} as const satisfies Errorish<'OkError'>
const AnyError = {name: 'Error', message: 'it happened'} as const satisfies Errorish<'Error'>
const UnknownError = {name: 'UnknownError', message: 'something happened'} as const satisfies Errorish<'UnknownError'>
const isFalsey = (it: unknown): it is falsey => !it
const isErrorish = (it: unknown): it is Errorish =>
it instanceof Error || (isAnyObject(it) && nameEndsWith('Error', it) && hasStringProp(it, 'message'))
Errorish.is = isErrorish
@subtleGradient
Copy link
Author

cc @steida I keep being compelled to play around with this pattern. Typed errors are totally changing how I think about everything!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment