stateful-value: Values with built-in states
Please see ARTICLE.md for the rationale of the package.
Installation
npm i -S stateful-value
Usage
To represent a value that could be:
- Unfulfilled: it has not been loaded/populated (e.g. AJAX, user input)
- Error: error encountered during loading operation
- Valid: it has been successfully loaded
import { StatefulValue } from "stateful-value";
let data: StatefulValue<string>;
if (isValid(data)) {
// data is guaranteed to be a string
console.log(data.length);
}
data = await loadData();
if (isError(data)) {
// data is guaranteed to be an Error (or subclass of Error) object
console.error(data.message);
}
API
StatefulValue<T>
Type Defines a type that can represent a value that is either unfulfilled, or is an error, or is valid.
isUnfulfilled(): boolean
Function Determines whether the value is undefined
or an Unfulfilled
object.
isError(): boolean
Function Determines whether the value is an Error
object.
isValid(): boolean
Function Determines whether the value is valid (i.e. an instance of type T
).
isNonNull(): boolean
Function Determines whether the value is valid and is not null
.
Note: null
is considered a valid value if T
contains it, e.g. StatefulValue<string | null>
.
getValue(): T | undefined
Function Returns the value if it is valid; otherwise, returns undefined
.
getError(): T | undefined
Function Returns the value if it is an Error
object; otherwise, returns undefined
.
resolveValue
Function async function resolveValue<T>(
callback: () => Promise<T>,
dependencies: StatefulValue<unknown>[] = []
): Promise<StatefulValue<T>>
Resolves a stateful value when all dependencies are valid.
- If any of the dependencies is an error, then return the first dependency error.
- If all dependencies are valid, then invoke the callback to get the target stateful value.
- Otherwise, returns
Unfulfilled
.