Skip to content

ootidea/result-type-ts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

96 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

result-type-ts

A modern TypeScript library for the so-called Result type.

Features

  • 0 dependencies
  • Provides many utility functions about the Result type
  • Well-tested
  • Works on both browsers and Node.js
  • Strict type inference

Usage

Here's a simple example of how to use this library:

import { Result } from 'result-type-ts'

const result: Result<number, string> = Math.random() < 0.5 ? Result.success(123) : Result.failure('error')

if (result.isSuccess) {
  console.log(result.value) // 123
} else {
  console.log(result.error) // error
}

API

Functions

Result.success(value)
Type <T>(value: T) => Result.Success<T>
Description Creates a successful result.

Example

const result = Result.success(123)
console.log(result.value) // 123
console.log(result.isSuccess) // true
console.log(result.isFailure) // false

Result.failure(error)
Type <E>(error: E) => Result.Failure<E>
Description Creates a failed result.

Example

const result = Result.failure('error')
console.log(result.error) // error
console.log(result.isFailure) // true
console.log(result.isSuccess) // false

Result.tryCatch(f)
Type <T>(f: () => T) => Result<T, unknown>
Description If the given function returns a value, a successful result is created. If it throws an exception, a failed result is created.

Example

const result = Result.tryCatch(() => 123)
console.log(result.value) // 123

const result2 = Result.tryCatch(() => {
  throw 'error'
})
console.log(result2.error) // error

Result.fromNullish(value)
Type <T>(value: T | null | undefined) => Result<T, null | undefined>
Description Convert a nullish value to a Result value.

Example

const result = Result.fromNullish(123);
console.log(result.value) // 123

const result2 = Result.fromNullish(null);
console.log(result2.error) // null
console.log(result2.isFailure) // true

Result.fromPromise(promise)
Type <T>(promise: PromiseLike<T>) => Promise<Result<T>>
Description Convert a Promise value to a Result value.

Example

const result = await Result.fromPromise(Promise.resolve(123))
console.log(result.value) // 123

const result2 = await Result.fromPromise(Promise.reject('error'))
console.log(result2.error) // error

Result.all(results)
Type <T, E>(results: Result<T, E>[]) => Result<T[], E>
Description Converts an array of Results into a single Result. If all results are successful, it returns a successful result of an array of values. Otherwise, it returns the first failed result.

Example

const result = await Result.all([Result.success(123), Result.success(456)])
console.log(result.value) // 123

const result2 = await Result.all([Result.success(123), Result.failure('error')])
console.log(result2.error) // error

const result3 = await Result.all([Result.failure('error'), Result.failure('error2')])
console.log(result3.error) // error

Types

Result.Success<T>
Represents a successful result type with a payload of type T.

Example

const result: Result.Success<number> = Result.success(123)

Result.Failure<E>
Represents a failed result type with an error value of type E.

Example

const result: Result.Failure<string> = Result.failure('error')

Result<T, E>
Shorthand for Result.Success<T> | Result.Failure<E> type. E is optional with a default value of unknown.

Example

const result: Result<number, string> = Math.random() > 0.5 ? Result.success(123) : Result.failure('error')

Properties

result.value
Type T | undefined
Description The payload of the successful result. If the result is a failure, it's undefined.

Example

const result = Result.success(123)
console.log(result.value) // 123

const result2 = Result.failure('error')
console.log(result2.value) // undefined

result.error
Type E | undefined
Description The payload of the failed result.

Example

const result = Result.success(123)
console.log(result.error) // undefined

const result2 = Result.failure('error')
console.log(result2.error) // error

result.isSuccess
Type boolean
Description Whether it is a successful result.

Example

const result = Result.success(123)
console.log(result.isSuccess) // true

const result2 = Result.failure('error')
console.log(result2.isSuccess) // false

result.isFailure
Type boolean
Description Whether it is a failed result.

Example

const result = Result.success(123)
console.log(result.isFailure) // false

const result2 = Result.failure('error')
console.log(result2.isFailure) // true

Methods

result.getOrThrow()
Type () => T
Description Returns this.value if it's a successful result, otherwise throws this.error.

Example

const result = Result.success(123)
console.log(result.getOrThrow()) // 123

const result2 = Result.failure('error')
try {
  result2.getOrThrow()
} catch (e) {
  console.log(e) // error
}

result.toUnion()
Type () => T | E
Description Returns the payload of the result value.

Example

const result = Result.success(123)
console.log(result.toUnion()) // 123

const result2 = Result.failure('error')
console.log(result2.toUnion()) // error

result.ifSuccess(f)
Type <T2>(f: (value: T) => T2) => T2 | undefined
Description Applies the given function to this.value if it's a successful result, otherwise returns undefined.

Example

const result = Result.success(123)
console.log(result.ifSuccess((value) => value * 2)) // 246

const result2 = Result.failure('error')
console.log(result2.ifSuccess((value) => value * 2)) // undefined

result.ifFailure(f)
Type <E2>(f: (error: E) => E2) => E2 | undefined
Description Applies the given function to result.error if it's a failed result, otherwise returns undefined.

Example

const result = Result.success(123)
console.log(result.ifFailure((error) => error + '!')) // undefined

const result2 = Result.failure('error')
console.log(result2.ifFailure((error) => error + '!')) // error!

result.match(f, g)
Type <T2, E2>((value: T) => T2, (error: E) => E2) => T2 | E2
Description Return the result of applying one of the given functions to the payload.

Example

const result = Result.success(123)
console.log(result.match((value) => value * 2, (error) => error + '!')) // 246

const result2 = Result.failure('error')
console.log(result2.match((value) => value * 2, (error) => error + '!')) // error!

result.map(f)
Type <T2>(f: (value: T) => T2) => Result<T2, E>
Description Creates a Result value by modifying the payload of the successful result using the given function

Example

const result = Result.success(123).map((value) => value * 2)
console.log(result.value) // 246

const result2 = Result.failure('error').map((value) => value * 2)
console.log(result2.error) // error

result.mapError(f)
Type <E2>(f: (error: E) => E2) => Result<T, E2>
Description Creates a Result value by modifying the payload of the failed result using the given function

Example

const result = Result.success(123).mapError((error) => error + '!')
console.log(result.value) // 123

const result2 = Result.failure('error').mapError((error) => error + '!')
console.log(result2.error) // error!

result.flatMap(f)
Type <T2, E2>(f: (value: T) => Result<T2, E2>) => Result<T2, E | E2>
Description Maps the payload of the successful result and flattens the nested Result type.

Example

const result = Result.success(123).flatMap((value) => Result.success(value * 2))
console.log(result.value) // 246

const result2 = Result.failure('error').flatMap((value) => Result.failure(value * 2))
console.log(result2.error) // error

result.flatMapAsync(f)
Type <T2, E2>(f: (value: T) => Result<T2, E2>) => Result<T2, E | E2>
Description Maps the payload of the successful result and flattens the nested async Result function.

Example

const result = await Result.success(123).flatMapAsync(async (value) => Result.success(value * 2))
console.log(result.value) // 246

const result2 = await Result.failure('error').flatMapAsync(async (value) => Result.failure(value * 2))
console.log(result2.error) // error

result.flatten()
Type () => Result<T, E | E2>
Description Flattens the nested Result type. For instance, it converts Result<Result<T, E>, E2> into Result<T, E | E2>.

Example

const result = Result.success(Result.success(123)).flatten()
console.log(result.value) // 246

const result2 = Result.success(Result.failure('error')).flatten()
console.log(result2.error) // error

const result3 = Result.failure('error').flatten()
console.log(result3.error) // error

result.assertErrorInstanceOf(ctor)
Type <C extends abstract new (..._: any) => any>(ctor: C) => Result<T, InstanceType<C>>
Description Asserts that the error value is an instance of the given class. If the error value is not an instance of the given class, it throws TypeError.

Example

const result: Result<number, Error> = Result.tryCatch(() => {
  if (Math.random() >= 0) {
    throw new Error('error')
  } else {
    return 123
  }
}).assertErrorInstanceOf(Error)
console.log(result.isFailure && result.error.message) // error