Skip to content

xstd-js/enum

Repository files navigation

npm (scoped) npm NPM npm type definitions coverage

Shows a black logo in light color mode and a white one in dark color mode.

@xstd/enum

Rust like enum types: exposes a way to declare and consume "unions" or "types" as plain objets.

NOTE: this is not Typescript enum.

Example

import { type Enum } from '@xstd/enum';

async function main() {
  /**
   * Calls `fetch` with the given url and returns a `Result` according to the Promise resolved state.
   * NOTE: `tryAsyncFnc` never rejects, thus it may be used as a replacement for a `try/catch` block.
   */
  const result: Result<number, string> = await tryAsyncFnc(fetch, 'https://example.com');
  
  if (isOk(result)) {
    console.log(result.value);
  } else {
    console.error(result.error);
  }
}

📦 Installation

yarn add @xstd/enum
# or
npm install @xstd/enum --save

📜 Documentation

Enum

interface Enum<GType extends string> {
  readonly type: GType;
}

Represents a type as an object.

Result

type Result<GValue, GError = unknown> = ResultOk<GValue> | ResultErr<GError>

Represents a value or an error. It may be used to represent the result of a function call, instead of relying on try/catch blocks.

ResultOk

interface ResultOk<GValue> extends Enum<'Ok'> {
  readonly value: GValue;
}

Represents a value returned by a function call.

ResultErr

interface ResultErr<GError = unknown> extends Enum<'Err'> {
  readonly error: GError;
}

Represents an error returned by a function call.

tryFnc

function tryFnc<GArguments extends readonly unknown[], GReturn>(
  fnc: (...args: GArguments) => GReturn,
  ...args: GArguments
): Result<GReturn>

Evaluates a function and returns a Result according to the function return's state.

Example:

const result: Result<string> = tryFnc(atob, 'invalid');

tryAsyncFnc

function tryAsyncFnc<GArguments extends readonly unknown[], GReturn, GError = unknown>(
  fnc: (...args: GArguments) => PromiseLike<GReturn> | GReturn,
  ...args: GArguments
): Promise<Result<GReturn, GError>>

Evaluates a function and returns a Result according to the Promise's resolved state.

Example:

const result: Result<Response> = await tryAsyncFnc(fetch, 'https://example.com');

promiseResult

function promiseResult<GReturn, GError = unknown>(
  promise: PromiseLike<GReturn>,
): Promise<Result<GReturn, GError>>

Returns a Result according to the Promise's resolved state.

Example:

const result: Result<Response> = await promiseResult(fetch('https://example.com'));

About

Rust like enum types

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published