UNPKG

@hazae41/box

Version:

Rust-like Box and similar objects for TypeScript

74 lines (71 loc) 2.02 kB
import { Nullable } from '../../libs/nullable/index.js'; import { Borrow } from '../borrow/index.js'; declare class MovedError extends Error { #private; readonly name: string; constructor(); } type BoxState = "owned" | "borrowed" | "dropped"; /** * An ownable and borrowable reference */ declare class Box<T extends Disposable> { #private; readonly value: T; /** * An ownable reference * @param value */ constructor(value: T); [Symbol.dispose](): void; [Symbol.asyncDispose](): Promise<void>; static create<T extends Disposable>(value: T): Box<T>; static createAsDropped<T extends Disposable>(value: T): Box<T>; get owned(): boolean; get borrowed(): boolean; get dropped(): boolean; /** * Get the value * @returns T */ get(): T; /** * Get the value or null-like if not owned * @returns T or null-like if not owned */ getOrNull(): Nullable<T>; /** * Get the value or throw if not owned * @returns T * @throws NotOwnedError if not owned */ getOrThrow(): T; checkOrNull(): Nullable<this>; checkOrThrow(): this; /** * Get the value and set this as moved or null-like if not owned * @returns T or null-like if not owned */ unwrapOrNull(): Nullable<T>; /** * Get the value and set this as moved or throw if not owned * @returns T * @throws BoxMovedError if not owned */ unwrapOrThrow(): T; /** * Move the value to a new box and set this one as moved or null-like if already moved * @returns Box<T> or null-like if moved */ moveOrNull(): Nullable<Box<T>>; /** * Move the value to a new box and set this one as moved or throw if already moved * @returns Box<T> * @throws BoxMovedError if already moved */ moveOrThrow(): Box<T>; borrowOrNull(): Nullable<Borrow<T>>; borrowOrThrow(): Borrow<T>; returnOrThrow(): void; } export { Box, type BoxState, MovedError };