@universal-apps/ts-utils
TypeScript icon, indicating that this package has built-in type declarations

1.1.3 • Public • Published

ts-utils

A typescript utility library to help utilize functional programming concepts by re-creating monads like Option (Scala), Either (Scala) and Result (Rust) in Typescript.

Check out the blog post for a good overview.

Installation

NPM package

npm i @universal-apps/ts-utils
# OR
pnpm i @universal-apps/ts-utils

Library

Option types

Either types

Result types

Result tuple types

Usage & Examples

// Option
const someValue: Option<number> = some(42) // { value: 42 }
const noValue: Option<number> = none() // {}

// Utilities to match on the Option type
matchOptionF({
    some: (value) => value,
    none: () => undefined,
})(someValue)

// Either
const rightFn = (): Either<Error, number> => right(42) // { value: 42 }
const leftFn = (): Either<Error, number> => left(new Error('bad')) // { error: Error('bad) }

// Utilities to match on the Either type
matchEitherF<Error, number, Error, number>({
    right: (result) => result,
    left: (err) => err,
})(rightFn)

// Result
const okFn = (): Result<number, Error> => ok(42) // { value: 42 }
const errFn = (): Result<number, Error> => err(new Error('bad')) // { error: Error('bad') }

// Utilities to match on the Result type
matchResultF({
    ok: (result) => result,
    err: (err) => err,
})(okFn())
// OR
matchResultF<number, Error, number, Error>({
    ok: (result) => result,
    err: (err) => err,
})(okFn())

// Result Tuple
const result: ResultT<number> = 42 // 1
const error: ErrorT = new Error('bad') // Error('bad')

const resultTuple: ResultTuple<number> = toTuple({ result }) // [42, undefined]
// OR
const resultTuple: ResultTuple<number> = toTuple({ error }) // [undefined, new Error('bad')]

// Say goodbye to try/catch and use it this way
const aPromise = async (): Promise<ResultTuple<number>> =>
    Promise.resolve(toTuple({ result: 42 }))

const fn = async (): Promise<any> => {
    const [result, error] = await aPromise()
    if (error) {
        // do something with error
        throw error
    } else {
        // do something with result
        console.log(`Result is ${result}`)
    }
}

More examples can be found here

Tests

The tests can be found here

pnpm run test
# or
pnpm run test:ui

Inspiration

Inspired by this article by Dan Imhoff.

Resources

fp-ts library

EffectTS library

pratica

Functional Programming Series on Youtube

Publishing

pnpm version <major|minor|patch>
pnpm publish --dry-run --publish-branch <current-branch>
pnpm publish

Package Sidebar

Install

npm i @universal-apps/ts-utils

Weekly Downloads

1

Version

1.1.3

License

MIT

Unpacked Size

18.5 kB

Total Files

13

Last publish

Collaborators

  • prashanthr