Skip to content

createContext

ts
createContext<T = unknown>(description?: string): ContextKey<T>

Creates a typed injection key.

Usage

ts
import { 
createContext
, type
Signal
} from '@studiometa/js-toolkit';
interface SliderApi {
state
:
Signal
<{
index
: number }>;
goNext
(): void;
} export const
SliderContext
=
createContext
<SliderApi>('slider');

Parameters

  • description (string, optional) — for debugging only.

Return value

  • ContextKey<T> — an opaque value carrying the phantom type T.

Why a value and not a string

The identity of the key is what resolves. Two keys with the same description are two different keys, so nothing collides — and the type parameter is what makes $inject(key) give a typed value with no cast at the call site.

Declare the key beside the interface it carries, and export both:

ts
// slider-context.ts
export interface SliderApi { … }
export const SliderContext = createContext<SliderApi>('slider');

Provider and consumer then import one module and agree by construction.

The default is unknown

createContext('name') with no type parameter gives ContextKey<unknown>, so $inject() resolves with unknown and the consumer has to narrow. Give it the type.

MIT Licensed