v0.0.14
utilities

Context

A type-safe wrapper around Svelte's Context API.

Example coming soon!

Usage

import { Context } from 'svxui';

// Create a context
const themeContext = new Context<string>('theme');

// Set context value
themeContext.set('dark');

// Get context value and throw error if not set
themeContext.get();

// Get context value with fallback if not set
themeContext.getOr('dark');

// Check if context is set
themeContext.exists();

// Get the context key
themeContext.key;

Type Definition

Context

export declare class Context<TContext> {
    /**
     * @param name The name of the context.
     */
    constructor(name: string);

    /**
     * The key used to get and set the context.
     *
     * @remarks
     * **Warning:** It is not recommended to use this value directly.
     * Using the raw key bypasses the type-safe API provided by this class.
     * Prefer using `exists()`, `get()`, `getOr()`, and `set()` methods instead.
     *
     * @internal Exposed for advanced use cases only.
     */
    get key(): symbol;

    /**
     * Checks whether this has been set in the context of a parent component.
     *
     * Must be called during component initialisation.
     */
    exists(): boolean;

    /**
     * Retrieves the context that belongs to the closest parent component.
     *
     * Must be called during component initialisation.
     *
     * @throws An error if the context does not exist.
     */
    get(): TContext;

    /**
     * Retrieves the context that belongs to the closest parent component,
     * or the given fallback value if the context does not exist.
     *
     * Must be called during component initialisation.
     */
    getOr<TFallback>(fallback: TFallback): TContext | TFallback;

    /**
     * Associates the given value with the current component and returns it.
     *
     * Must be called during component initialisation.
     */
    set(context: TContext): TContext;
}

Credits

Runed