Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,44 @@
# Changelog

## [1.0.0]

- Removed multiple named exports from the base library in favor of
one singular named export (e.g. `result` and `option`)
- If using those named exports (e.g. `err()`) then you simply have to
import the namespaced export and use it as an object. (e.g. `result.err()`)
- `import {option, result} from '@dbidwell94/ts-utils';`

## [0.7.0]

- Added new "static" functions to help with `SerializableOption`
- `option.isSome(val)`
- `option.isNone(val)`

## [0.6.3]

- Update dev-dependencies to latest versions to resolve audit issues
- Update `ts-jest` to version 29.2.6
- Update `typescript` to version 5.8.2

## [0.6.2]

- Refactor `unknown` function signature to accept optional or null parameters
- This change allows for more flexible usage of the `unknown` function when dealing with potentially null or undefined values
- This change allows for more flexible usage of the `unknown` function when
dealing with potentially null or undefined values
- Add documentation for the `unknown` function

## [0.6.1]

- Add new utility function `unknown` to the `Option` namespace
- This function constructs an `Option<T>` type from an unknown value, returning a `Some<T>` if the value is not null or undefined, otherwise returning `None`
- This function constructs an `Option<T>` type from an unknown value,
returning a `Some<T>` if the value is not null or undefined, otherwise
returning `None`

## [0.6.0]

- Add new utility function `andThen` for both `Result` and `Option` types
- Added function overload for `fromPromise` which will convert a `Result<Promise<T>, E>` to a `Promise<Result<T, E>>`
- Added function overload for `fromPromise` which will convert a
`Result<Promise<T>, E>` to a `Promise<Result<T, E>>`

## [0.5.2]

Expand All @@ -29,7 +50,8 @@

## [0.5.0]

- Changed function signature of `fromSerializableOption` to accept a possibly undefined object
- Changed function signature of `fromSerializableOption` to accept a possibly
undefined object
- If undefined is provided, a `None` type is returned.
- Changed conditional for `fromSerializableOption` to be more resilient with
possibly bad types passed as a parameter
Expand Down
118 changes: 51 additions & 67 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,95 +1,78 @@
# TypeScript Rust-Like Utility Types
# Typescript Rust-Like Utility Types

A TypeScript library that provides utility types inspired by Rust's powerful type system, including `Result<T, E>` and `Option<T>`. These types help to enhance type safety and improve error handling in TypeScript applications.
A Typescript library that provides utility types inspired by Rust's powerful type
system, including `Result<T, E>` and `Option<T>`. These types help to enhance
type safety and improve error handling in Typescript applications.

## Installation

You can install the library via npm:
You can install the library via `npm`:

```bash
npm install @dbidwell94/ts-utils
npm i @dbidwell94/ts-utils
```

## Usage

### Option<T>
```bash
yarn add @dbidwell94/ts-utils
```

The `Option<T>` type is used to represent a value that can either be `Some(value)` or `None`. This is useful for scenarios where a value may or may not be present.
```bash
pnpm add @dbidwell94/ts-utils
```

```typescript
import { Option, option } from '@dbidwell94/ts-utils';
## Documentation

// Example usage
function findUserById(id: string): Option<User> {
const user = database.find(user => user.id === id);
return user ? option.some(user) : option.none();
}
Documentation is provided via `typedoc` and is published [on GitHub Pages](https://dbidwell94.github.io/ts-utils/)

const userOption = findUserById('123');
## Quick Start

if (userOption.isSome()) {
console.log(`Found user: ${userOption.value}`);
} else {
console.log('User not found');
}
```
### Option

### Result<T, E>
```ts
import { option, Option } from "@dbidwell94/ts-utils";

The `Result<T, E>` type is used to represent the result of an operation that can either succeed with a value of type `T` or fail with an error of type `E`. This is ideal for handling operations that can fail.
const myOption = option.some(123);

```typescript
import { Result, result } from '@dbidwell94/ts-utils';

// Example usage
function divide(a: number, b: number): Result<number> { // Result<T> can be used instead of `Result<T, Error>`, however you can make the 2nd type param anything that extends `Error`
if (b === 0) {
return result.err("Cannot divide by zero");
}
return result.ok(a / b);
function doSomethingWithOptions(optionParam: Option<number>) {
if (optionParam.isSome()) {
console.log(`Option value is ${optionParam.value}`);
} else {
console.log("The provided Option has no value");
}
}

const divideResult = divide(10, 0);
doSomethingWithOptions(myOption); // Option value is 123
doSomethingWithOptions(option.none()); // The provided Option has no value

if (divideResult.isOk()) {
console.log(`Result: ${result.value}`);
} else {
console.error(`Error: ${result.error}`);
function doSomethingNullishValue(val: number | null | undefined) {
doSomethingWithOptions(option.unknown(val));
}
```

## API Reference

### `Option<T>`
doSomethingNullishValue(null); // The provided Option has no value
```

- `some(value: T)`: Represents a value that is present.
- `none()`: Represents the absence of a value.
- `isSome()`: Returns `true` if the option contains a value.
- `isNone()`: Returns `true` if the option does not contain a value.
- `unwrap()`: Returns the value contained in `Some`, or throws an error if it is `None`.
- `unwrapOr(err: E)`: Returns the value contained in `Some`, or throws the provided error if it is `None`.
- `map(newValue: NewT)`: Maps the value of `T` into a `NewT` if the provided value is `Some`.
- `serialize()`: Converts the `Option` into a serializable Option without any helper functions. Useful if you want to store the `Option` in Redux, or send the value over the net
- `fromSerializableOption(option: SerializableOption)`: Converts a `SerializableOption` into an `Option` with all the helper functions
### Result

```ts
import { result, Result } from "@dbidwell94/ts-utils";

### `Result<T, E>`
const myResult = result.ok(123);

- `ok(value: T)`: Represents a successful result.
- `err(error: E)`: Represents a failed result.
- `isOk()`: Returns `true` if the result is successful.
- `isError()`: Returns `true` if the result is an error.
- `unwrap()`: Returns the value contained in `Ok`, or throws an error if it is `Err`.
- `unwrapOr(default: T)`: Returns the value contained in `Ok`, or returns the default value `T`.
- `unwrapOrElse(error: E)`: Returns the value contained in `Ok`, or throws the provided error `E`.
- `ok()`: Converts the `Result<T, E>` into an `Option<T>`.
- `err()`: Converts the `Result<T, E>` into an `Option<E>`.
- `mapOk(newValue: NewT)`: Maps the value of `T` into a `NewT`, returning a new `Result<NewT, E>`.
- `mapErr(newError: NewE)`: Maps the error `E` into a `NewE`, returning a new `Result<T, NewE>`.
function doSomethingWithResult(resultParam: Result<number>) {
if (resultParam.isOk()) {
console.log(`The provided value was ${resultParam.value}`);
} else {
console.log(
`The provided Result errored with ${resultParam.error.toString()}`,
);
}
}
```

## Contributing

Contributions are welcome! Please open an issue or submit a pull request if you'd like to add features or fix bugs.
Contributions are welcome! Please open an issue or submit a pull request if
you'd like to add features or fix bugs.

1. Fork the repository.
2. Create a new branch (`git checkout -b feature-branch`).
Expand All @@ -100,9 +83,10 @@ Contributions are welcome! Please open an issue or submit a pull request if you'

## License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file
for details.

## Acknowledgements

Inspired by the elegant type system of Rust, this library aims to bring similar concepts to TypeScript for improved type safety and error handling.

Inspired by the elegant type system of Rust, this library aims to bring similar
concepts to Typescript for improved type safety and error handling.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dbidwell94/ts-utils",
"version": "0.7.0",
"version": "1.0.0",
"description": "A collection of helpful TypeScript utilities with the aim of having limited production dependencies.",
"main": "dist/index.js",
"files": [
Expand Down