A zero-dependency Result type for TypeScript
$ npm install @haideralsh/ts-result
Example adapted from the Elm guide
import { Result, Ok, Err } from '@haideralsh/ts-result'
function isReasonableAge(age: number): Result<number, string> {
if (age < 0) return Err('Please try again after you are born.')
if (age > 135) return Err('Are you some kind of a turtle?')
return Ok(age)
}
const ageResult = isReasonableAge(9000)
if (ageResult.ok === true) {
const age = ageResult.get()
} else {
console.error(ageResult.getError()) // Are you some kind of a turtle?
}
A Result
type is the result of a computation that may fail. The type is used
for returning and propagating errors. It is helpful to give additional
information when things go wrong.
Let us say that we want to insert a user into our database and return the user entity back:
function addUser(name: string, email: string): User {
const { uuid } = db.query('insert into user values (?, ?)', name, email)
return User.getById(uuid)
}
However, an insertion operation can sometimes fail. There is no way for the caller of the function above to know that such failure could happen without diving into the implementation of the function.
We could handle the potential failure ourselves and return nothing when the failure happens:
function addUser(name: string, email: string): User | null {
try {
const { uuid } = db.query('insert into user values (?, ?)', name, email)
return User.getById(uuid)
} catch (err) {
return null
}
}
If TypeScript is configured properly, this could be an improvement since
TypeScript will warn the caller that the result may be null
. However, it
doesn't provide them a way to know what is the error that occurred.
We can change the null to be a string instead:
function addUser(name: string, email: string): User | string {
try {
const { uuid } = db.query('insert into user values (?, ?)', name, email)
return User.getById(uuid)
} catch (err) {
return err.message
}
}
This is not any better because now we lose the TypeScript null warning and we
still have to check if the returned type is a string
or a User
which can be
non-trivial.
This problem becomes more pronounced when both the okay and error results share
the same type. Let us say we only want to return the user identifier instead of
the whole User
object:
function addUser(name: string, email: string): string {
try {
const { uuid } = db.query('insert into user values (?, ?)', name, email)
return uuid
} catch (err) {
return err.message
}
}
Now we can not tell if the string returned is the user's UUID or the error message.
This is where the Result
type comes in. It provides a more elegant way for
handling potentially erroneous results.
We can rewrite the above example into this:
import { Result, Ok, Err } from '@haideralsh/ts-result'
function addUser(name: string, email: string): Result<string, string> {
try {
const { uuid } = db.query('insert into user values (?, ?)', name, email)
return Ok(uuid)
} catch (err) {
return Err(err.message)
}
}
Now the caller of this function can use the ok
property to know which type of
result is returned
const insertResult = addUser('Micheal', 'micheal@example.com')
if (insertResult.ok === true) {
const userId = insertResult.get() // The user's UUID if the insertion succeeded
} else {
const errorMsg = insertResult.getError() // The error message if the insertion failed
}
A Result
type accepts two generics. The first (T
) must match the value type
passed to Ok
, while the second (E
) must match the value type passed to
Err
.
A function with a return type Result
must return either an Ok
or Err
or
both of them matching their respective types.
import { Result, Ok, Err } from '@haideralsh/ts-result'
function divide(a: number, b: number): Result<number, string> {
if (b === 0) {
return Err('Division by zero!')
}
return Ok(a / b)
}
We can use the ok
property in order to know if the result was wrapped with an
Ok
or an Err
The property ok
will be true
if a result was wrapped with an Ok
or false
if it was wrapped with Err
.
Example (Ok)
// See `divide` implementation above
const divideResult = divide(1, 1)
console.log(divideResult.ok) // true
Example (Err)
// See `divide` implementation above
const divideResult = divide(1, 0)
console.log(divideResult.ok) // false
The getOr
function will return the ok value if the result was wrapped with an
Ok
or the supplied default value if it was wrapped with Err
.
Example (Ok)
// See `divide` implementation above
const divideResult = divide(1, 1)
console.log(divideResult.getOr('foo')) // 1
Example (Err)
// See `divide` implementation above
const divideResult = divide(1, 0)
console.log(divideResult.getOr('foo')) // foo
The getOrThrow
function will return the ok value if the result was wrapped
with an Ok
or throw an error using the Err
value as a message. You can
supply the error or the error message to throw as an optional parameter.
Example (Ok)
// See `divide` implementation above
const divideResult = divide(1, 1)
console.log(divideResult.getOrThrow('foo')) // 1
Example (Err)
// See `divide` implementation above
const divideResult = divide(1, 0)
console.log(divideResult.getOrThrow()) // Uncaught Error: Division by zero!
console.log(divideResult.getOrThrow('foo')) // Uncaught Error: foo
console.log(divideResult.getOrThrow(new MyCustomError('foo'))) // Uncaught MyCustomError: foo
The getOrRun
function will return the ok value if the result was wrapped with
an Ok
or run a function if the result was wrapped with an Err
.
Example (Ok)
// See `divide` implementation above
const divideResult = divide(1, 1)
function greeting() {
return 'Hello world!'
}
console.log(divideResult.getOrRun(greeting)) // 1
Example (Err)
// See `divide` implementation above
const divideResult = divide(1, 0)
function greeting() {
return 'Hello world!'
}
console.log(divideResult.getOrRun(greeting)) // Hello world!
The mapWithDefault
function will apply a function on the ok value if the
result was wrapped with an Ok
or the error value if the result was wrapped
with an Err
. The return type will be the same as the supplied function to map.
Example (Ok)
// See `divide` implementation above
const divideResult = divide(1, 1)
function addOne(num: number) {
return num + 1
}
console.log(divideResult.mapWithDefault(10, addOne)) // 2
Example (Err)
// See `divide` implementation above
const divideResult = divide(1, 0)
function addOne(num: number) {
return num + 1
}
console.log(divideResult.mapWithDefault(10, addOne)) // 11
The Ok
function accepts a value of type T
that must match the T
generic
type passed to Result<T, E>
The get
function will unwrap the value wrapped with an Ok
. You have to check
if the ok
property is true
first before being able to use get
.
Example
const okResult = OK('foo')
if (okResult.ok === true) console.log(okResult.get()) // foo
The map
function will unwrap and apply the supplied function on the value
wrapped with an Ok
. The supplied function must accept the same type as the
wrapped value type. The return type of the map
function will be the same as
the one of the supplied function. You have to check if the ok
property is
true
first before being able to use map
.
Example
const okResult = OK('foo')
function capitalize(str: string) {
return str.toUpperCase()
}
if (okResult.ok === true) console.log(okResult.map(capitalize)) // FOO
The Err
function accepts a value of type E
that must match the E
generic
type passed to Result<T, E>
The getError
function will unwrap the value wrapped with an Err
. You have to
check if the ok
property is false
first before being able to use getError
.
Example
const errResult = Err('foo')
if (errResult.ok === false) console.log(errResult.getError()) // foo