context
Version:
Lightweight context propagation for JavaScript and TypeScript. Create a scoped storage object, run code inside it, and read the active value anywhere down the call stack - without depending on React.
27 lines (25 loc) • 1.01 kB
text/typescript
import { CB, Maybe, Nullable } from "vest-utils";
//#region src/context.d.ts
/**
* Base context interface.
*/
declare function createContext<T>(defaultContextValue?: T): CtxApi<T>;
/**
* Cascading context - another implementation of context, that assumes the context value is an object.
* When nesting context runs, the the values of the current layer merges with the layers above it.
*/
declare function createCascade<T extends Record<string, unknown>>(init?: (value: Partial<T>, parentContext: Maybe<T>) => Nullable<T>): CtxCascadeApi<T>;
type ContextConsumptionApi<T> = {
use: () => T;
useX: (errorMessage?: string) => T;
};
type CtxApi<T> = ContextConsumptionApi<T> & {
run: <R>(value: T, cb: () => R) => R;
};
type CtxCascadeApi<T> = ContextConsumptionApi<T> & {
run: <R>(value: Partial<T>, fn: () => R) => R;
bind: <Fn extends CB>(value: Partial<T>, fn: Fn) => Fn;
};
//#endregion
export { CtxApi, CtxCascadeApi, createCascade, createContext };
//# sourceMappingURL=context.d.mts.map