Rust like enum types: exposes a way to declare and consume "unions" or "types" as plain objets.
NOTE: this is not Typescript
enum.
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);
}
}yarn add @xstd/enum
# or
npm install @xstd/enum --saveinterface Enum<GType extends string> {
readonly type: GType;
}Represents a type as an object.
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.
interface ResultOk<GValue> extends Enum<'Ok'> {
readonly value: GValue;
}Represents a value returned by a function call.
interface ResultErr<GError = unknown> extends Enum<'Err'> {
readonly error: GError;
}Represents an error returned by a function call.
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');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');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'));