Package Exports
- unenum
- unenum/global
- unenum/global.enum
- unenum/global.future
- unenum/global.result
Readme
unenum
A 0kb, Rust-like Enum/ADT mechanism for TypeScript with zero runtime requirements.
Overview
TypeScript should have a more versitile and ergonomic Enum/ADT mechanism that
feels like native utility, as opposed its
limited,
misused,
and redundant built-in enum
keyword which can be mostly replaced with a plain key-value mapping object
using as const.
Introducing unenum; a Rust-inspired, discriminable Enum/ADT type generic,
featuring:
- Zero dependencies;
unenumis extremely lightweight. - Zero runtime requirements;
unenumcan be completely compiled away -- no runtime or bundle size cost. Enumvariants that can define custom per-instance data; impossible with native TypeScriptenums.
unenum wants to feel like a native TypeScript utility type, like a
pattern, rather than a library:
Enums are defined astypestatements; instead of factory functions.Enums are instantiated with plain object{ ... }syntax; instead of constructors.Enums can be consumed (and narrowed) with plainifstatements; instead of imported match utilities.
Here's an example of unenum's Enum compared with Rust's
enum:
// TypeScript
type WebEvent = Enum<{
// Unit
PageLoad: undefined;
PageUnload: undefined;
// Tuple (not practical; use object instead)
KeyPress: { key: string };
Paste: { content: string };
// Object
Click: { x: number; y: number };
}>
const event: WebEvent = { is: "PageLoad" };
const event: WebEvent = { is: "PageUnload" };
const event: WebEvent = { is: "KeyPress", key: "x" };
const event: WebEvent = { is: "Paste", content: "..." };
const event: WebEvent = { is: "Click", x: 10, y: 10 };
function inspect(event: WebEvent) {
if (event.is === "PageLoad") console.log(event);
else if (event.is === "PageUnload") console.log(event);
else if (event.is === "KeyPress") console.log(event, event.key);
else if (event.is === "Paste") console.log(event, event.content);
else if (event.is === "Click") console.log(event, event.x, event.y);
}
|
// Rust
enum WebEvent {
// Unit
PageLoad,
PageUnload,
// Tuple
KeyPress(char),
Paste(String),
// Struct
Click { x: i64, y: i64 },
}
let event = WebEvent::PageLoad;
let event = WebEvent::PageUnload;
let event = WebEvent::KeyPress('x')
let event = WebEvent::Paste("...".to_owned());
let event = WebEvent::Click { x: 10, y: 10 };
fn inspect(event: WebEvent) {
match event {
WebEvent::PageLoad => println!(event),
WebEvent::PageUnload => println!(event),
WebEvent::KeyPress(c) => println!(event, c),
WebEvent::Paste(s) => println!(event, s),
WebEvent::Click { x, y } => println!(event, x, y),
}
}
|
Installation
npm install unenumFor Applications (Global):
import "unenum/global";For Libraries (Imported):
import type { Enum, ... } from "unenum";Enum<Variants>
Creates a union of mutually exclusive, discriminable variants.
import "unenum/global.enum"; // global
import type { Enum } from "unenum"; // imported
type Foo = Enum<{
A: undefined;
B: { b: string };
C: { c: number };
}>;
-> | { is: "A" }
| { is: "B"; b: string }
| { is: "C"; c: number }Enum.Keys<Enum>
Infers all possible variants' keys of the given Enum.
type Foo = Enum<{ A: undefined; B: { b: string }; C: { c: number } }>;
Enum.Keys<Foo>
-> "A" | "B" | "C"Enum.Values<Enum>
Infers all possible variants' values of the given Enum.
type Foo = Enum<{ A: undefined; B: { b: string }; C: { c: number } }>;
Enum.Values<Foo>
-> | { b: string }
| { c: number }Enum.Props<Enum, All?>
Infers only common variants' properties' names of the given Enum. If All is
true, then all variants' properties' names are inferred.
type Foo = Enum<{ A: undefined; B: { x: string }; C: { x: string; y: number } }>;
Enum.Props<Foo>
-> "x"
Enum.Props<Foo, true>
-> "x" | "y"Enum.Pick<Enum, VariantKeys>
Narrows a given Enum by including only the given variants by key.
type Foo = Enum<{ A: undefined; B: { b: string }; C: { c: number } }>;
Enum.Pick<Foo, "A" | "C">
-> | { is: "A" }
| { is: "C"; c: number }Enum.Omit<Enum, VariantKeys>
Narrows a given Enum by excluding only the given variants by key.
type Foo = Enum<{ A: undefined; B: { b: string }; C: { c: number } }>;
Enum.Omit<Foo, "A" | "C">
-> | { is: "B"; b: string }Included Enums
Result<Value?, Error?>
Represents either success value (Ok) or failure error (Error).
Result uses value?: never and error?: never to allow for shorthand access
to .value or .error if you want to safely default to undefined if either
property is not available.
import "unenum/global.result"; // global
import type { Result } from "unenum"; // imported
Result
-> | { is: "Ok"; value: unknown; error?: never }
| { is: "Error"; error: unknown; value?: never }
Result<number>
-> | { is: "Ok"; value: number; error?: never }
| { is: "Error"; error: unknown; value?: never }
Result<number, "FetchError">
-> | { is: "Ok"; value: number; error?: never }
| { is: "Error"; error: "FetchError"; value?: never }const getUser = async (name: string): Promise<Result<User, "NotFound">> => {
return { is: "Ok", value: user };
return { is: "Error", error: "NotFound" };
}
const $user = await getUser("foo");
if ($user.is === "Error") { return ... }
const user = $user.value;
const $user = await getUser("foo");
const userOrUndefined = $user.value;
const userOrUndefined = $user.is === "Ok" ? $user.value : undefined;
const $user = await getUser("foo");
const userOrDefault = $user.value ?? defaultUser;
const userOrDefault = $user.is === "Ok" ? $user.value : defaultUser;Based on Rust's
Result enum.
Note
You may find it useful to name container-like
Enumvalues (e.g. ofResults andFutures) with a$prefix (e.g.$user) before unwrapping the desired value into non-prefixed value (e.g.const user = $user.value).
Future<ValueOrEnum?>
Represents an asynchronous value that is either loading (Pending) or
resolved (Ready). If defined with an Enum type, Future will omit its
Ready variant in favour of the "non-pending" Enum's variants.
_Future uses value?: never to allow for shorthand access to .value if you
want to safely default to undefined if it is not available. If using with an
Enum type, all its common properties will be extended as ?: never
properties on the Pending variant to allow for shorthand undefined access
also. (See Enum.Props.)
import type { Future } from "unenum"; // imported
Future
-> | { is: "Pending"; value?: never }
| { is: "Ready"; value: unknown }
Future<string>
-> | { is: "Pending"; value?: never }
| { is: "Ready"; value: string }
Future<Result<number>>
-> | { is: "Pending"; value?: never; error?: never }
| { is: "Ok"; value: number; error?: never }
| { is: "Error"; error: unknown; value?: never }const useRemoteUser = (name: string): Future<Result<User, "NotFound">> => {
return { is: "Pending" };
return { is: "Ok", value: user };
return { is: "Error", error: "NotFound" };
};
const $user = useRemoteUser("foo");
if ($user.is === "Pending") { return <Loading />; }
if ($user.is === "Error") { return <Error />; }
const user = $user.value;
return <View user={user} />;
const $user = useRemoteUser("foo");
const userOrUndefined = $user.value;
const userOrUndefined = $user.is === "Ok" ? $user.value : undefined;
const $user = useRemoteUser("foo");
const userOrDefault = $user.value ?? defaultUser;
const userOrDefault = $user.is === "Ok" ? $user.value : defaultUser;Based on Rust's
Future trait and
Poll enum.
Utils
safely(fn) -> Result
Executes a given function and returns a Result that wraps its normal return
value as Ok and any thrown errors as Error. Supports async/Promise
returns.
import { safely } from "unenum"; // runtime
safely(() => JSON.stringify(...))
-> Result<string>
safely(() => JSON.parse(...))
-> Result<unknown>
safely(() => fetch("/endpoint").then(res => res.json() as Data))
-> Promise<Result<Data>>