Skip to content

Context

Stores Effect services in typed maps.

A Context holds service implementations under Context.Service or Context.Reference keys, and its type records which keys are present. Effects use contexts as their environment, so services can be provided once instead of passed through every function call. This module includes helpers for creating keys, building contexts, adding and reading services, merging contexts, and selecting or removing services.

28 exports Added in v2.0.0 Source

Combining

add

Added in v2.0.0 Source

Adds a service to a given Context.

When to use

Use when you need to store a known service value in a Context.

Details

If the context already contains the same service key, the new service replaces the previous one.

See

  • addOrOmit for adding or removing a service from an Option

Signature

declare const add: {
  <I, S>(
    key: Key<I, S>,
    service: NoInfer<S>,
  ): <Services>(self: Context<Services>) => Context<I | Services>;
  <Services, I, S>(
    self: Context<Services>,
    key: Key<I, S>,
    service: NoInfer<S>,
  ): Context<Services | I>;
};

addOrOmit

Added in v4.0.0 Source

Adds or removes a service depending on an Option.

When to use

Use when you need to add or omit a Context service based on an Option.

Details

When service is Option.some, the value is stored for the key. When it is Option.none, the key is removed from the returned Context.

See

  • add for always storing a service value

Signature

declare const addOrOmit: {
  <I, S>(
    key: Key<I, S>,
    service: Option<NoInfer<S>>,
  ): <Services>(self: Context<Services>) => Context<Exclude<Services, I>>;
  <Services, I, S>(
    self: Context<Services>,
    key: Key<I, S>,
    service: Option<NoInfer<S>>,
  ): Context<Exclude<Services, I>>;
};

merge

Added in v2.0.0 Source

Merges two Contexts into one.

When to use

Use when you need to combine two contexts.

Details

When both contexts contain the same service key, the service from that overrides the service from self.

See

  • mergeAll for merging more than two contexts at once

Signature

declare const merge: {
  <R1>(that: Context<R1>): <Services>(self: Context<Services>) => Context<R1 | Services>;
  <Services, R1>(self: Context<Services>, that: Context<R1>): Context<Services | R1>;
};

mergeAll

Added in v3.12.0 Source

Merges any number of Contexts into one.

When to use

Use when you need to combine a variadic list of contexts.

Details

When multiple contexts contain the same service key, the service from the last context with that key is kept.

See

  • merge for merging two contexts

Signature

declare function mergeAll<T extends Array<unknown>>(
  ...ctxs: [...Array<{ [K in string | number | symbol]: Context<T[K]> }>]
): Context<T[number]>;

Constructors

empty

Added in v2.0.0 Source

Returns an empty Context.

Signature

declare function empty(): Context<never>;

make

Added in v2.0.0 Source

Creates a new Context with a single service associated to the key.

Signature

declare function make<I, S>(key: Key<I, S>, service: NoInfer<S>): Context<I>;

makeUnsafe

Added in v4.0.0 Source

Creates a Context from an existing service map.

When to use

Use when constructing a low-level Context from a trusted map whose lifecycle you control.

Gotchas

The provided map is retained without copying and must not be mutated after construction. Prefer empty, make, add, or merge for normal Context construction.

Signature

declare function makeUnsafe<Services = never>(
  mapUnsafe: ReadonlyMap<string, any>,
): Context<Services>;

Filtering

omit

Added in v2.0.0 Source

Returns a new Context with the specified service keys removed.

When to use

Use when you want to remove a denylist of services from a Context.

See

  • pick for keeping selected services

Signature

declare function omit<S extends readonly Array<Key<any, any>>>(...keys: S): <Services>(self: Context<Services>) => Context<Exclude<Services, Identifier<S[number]>>>

pick

Added in v2.0.0 Source

Returns a new Context that contains only the specified services.

When to use

Use when you want to keep an allowlist of services in a Context.

See

  • omit for removing selected services

Signature

declare function pick<S extends readonly Array<Key<any, any>>>(...services: S): <Services>(self: Context<Services>) => Context<Services & Identifier<S[number]>>

Getters

get

Added in v2.0.0 Source

Gets a service from the context that corresponds to the given key.

When to use

Use when you need type-checked access to a service already included in the context type.

See

Signature

declare const get: {
  <Services, I, S>(service: Key<I, S>): (self: Context<Services>) => S;
  <Services, I, S>(self: Context<Services>, service: Key<I, S>): S;
};

getOption

Added in v2.0.0 Source

Gets the service for a key safely wrapped in an Option.

When to use

Use when you need to read a Context service as an Option so absence is represented as data.

Details

Returns Option.some when the service is stored in the context. If the key is a Context.Reference and no override is stored, returns Option.some of the cached default value. Missing non-reference keys return Option.none.

See

  • getOrElse for returning a fallback value directly

Signature

declare const getOption: {
  <S, I>(service: Key<I, S>): <Services>(self: Context<Services>) => Option<S>;
  <Services, S, I>(self: Context<Services>, service: Key<I, S>): Option<S>;
};

getOrElse

Added in v3.7.0 Source

Gets the service for a key, or evaluates the fallback when a non-reference key is absent.

When to use

Use when you need a fallback for a missing Context.Service key while still resolving Context.Reference defaults.

Details

If the key is a Context.Reference and no override is stored in the context, its cached default value is returned instead of the fallback.

Gotchas

The fallback is not evaluated for missing Context.Reference keys because references resolve to their default value.

See

  • getOption for returning Option.none when a non-reference key is missing

Signature

declare const getOrElse: {
  <S, I, B>(key: Key<I, S>, orElse: LazyArg<B>): <Services>(self: Context<Services>) => S | B;
  <Services, S, I, B>(self: Context<Services>, key: Key<I, S>, orElse: LazyArg<B>): S | B;
};

Returns the service currently stored for a key, or undefined when the key is absent.

When to use

Use when you need to read the service stored for a key without resolving Context.Reference defaults.

Gotchas

This is a raw lookup and does not resolve default values for Context.Reference keys.

See

  • getOption for a reference-aware optional lookup

Signature

declare const getOrUndefined: {
  <S, I>(key: Key<I, S>): <Services>(self: Context<Services>) => S | undefined;
  <Services, S, I>(self: Context<Services>, key: Key<I, S>): S | undefined;
};

Guards

isContext

Added in v2.0.0 Source

Checks whether the provided argument is a Context.

When to use

Use to narrow an unknown value before passing it to APIs that require a Context.

Details

This checks the runtime Context marker and does not inspect which services the context contains.

Gotchas

This guard only proves that the value is a Context; it does not prove that any specific service is present.

See

  • isKey for checking service keys
  • isReference for checking references with defaults

Signature

declare function isContext(u: unknown): u is Context<never>;

isKey

Added in v4.0.0 Source

Checks whether the provided argument is a Key.

Signature

declare function isKey(u: unknown): u is Key<any, any>;

isReference

Added in v3.11.0 Source

Checks whether the provided argument is a Reference.

Signature

declare function isReference<I, S>(u: Key<I, S>): u is Reference<S>;

Models

Context interface

Added in v2.0.0 Source

Immutable collection of service implementations used for dependency injection in Effect programs.

Details

The type parameter tracks the service identifiers available in the context. At runtime, services are stored by each key's string key.

Signature

interface Context<in Services> extends Equal, Pipeable, Inspectable {
  readonly "~effect/Context": {
    readonly _Services: Contravariant<Services>;
  };
  readonly mapUnsafe: ReadonlyMap<string, any>;
}

Key interface

Added in v4.0.0 Source

Typed identifier for a service stored in a Context.

When to use

Use as the typed handle for storing, retrieving, and requiring a specific service in a Context.

Details

Identifier tracks the requirement in Effect types, while Shape is the service implementation retrieved by the key. A key is also an Effect value, so yielding it inside Effect.gen retrieves the service from the current fiber context.

See

  • Service for creating required service keys
  • Reference for creating service keys with default values

Signature

interface Key<out Identifier, out Shape> extends Effect<Shape, never, Identifier> {
  readonly "~effect/Context/Service": "~effect/Context/Service";
  Identifier: Identifier;
  readonly key: string;
  readonly Service: Shape;
  readonly stack?: string;
}

Other

Service

Added in v2.0.0 Source

Namespace containing utility types for Context service keys.

ServiceClass

Added in v4.0.0 Source

Namespace containing helper types for class-style Context.Service declarations.

Services

Reference

Added in v3.11.0 Source

Creates a context key with a default value.

When to use

Use when you need to define a context key with a lazily computed default value.

Details

Context.Reference allows you to create a key that can hold a value. You can provide a default value for the service, which will automatically be used when the context is accessed, or override it with a custom implementation when needed. The default value is computed lazily and cached on the reference.

See

  • Service for required services without default values

Signature

declare const Reference: <Service>(
  key: string,
  options: {
    readonly defaultValue: () => Service;
  },
) => Reference<Service>;

Reference interface

Added in v3.11.0 Source

Service key with a lazily computed default value.

Details

When a Reference is requested from a Context that does not contain an override, Context getters that resolve references return the cached default value instead of failing.

Signature

interface Reference<in out Shape> extends Service<never, Shape> {
  constructor(_: never);
  readonly "~effect/Context/Reference": "~effect/Context/Reference";
  readonly defaultValue: () => Shape;
  [iterator](): EffectIterator<Reference<Shape>>;
}

Service

Added in v4.0.0 Source

Creates a Context service key.

When to use

Use when you need to define a context service key for a dependency that must be provided by the surrounding context.

Details

Call Context.Service("Key") for a function-style key, or use the two-stage form Context.Service<Self, Shape>()("Key") for class-style service declarations. The returned key can be yielded as an Effect and passed to Context.make, Context.add, and the Context getter functions.

Gotchas

The string key is the runtime identity of the service. Reusing the same key string for unrelated services makes them occupy the same slot in a Context.

See

  • Reference for service keys with default values

Signature

declare const Service: {
  <Identifier, Shape = Identifier>(key: string, options?: {}): Service<Identifier, Shape>;
  <Self, Shape>(): <Identifier extends string, E, R = unassigned, Args extends readonly Array<any> = never>(id: Identifier, options?: {
    readonly make?: (...args: Args) => Effect<Shape, E, R> | Effect<Shape, E, R>;
  }) => ServiceClass<Self, Identifier, Shape> & [unassigned] extends [R] ? unknown : {
    readonly make: [Args] extends [never] ? Effect<Shape, E, R> : (...args: Args) => Effect<Shape, E, R>;
  };
  <Self>(): <Identifier extends string, Make extends Effect<any, any, any> | (...args: any) => Effect<any, any, any>>(id: Identifier, options: {
    readonly make: Make;
  }) => ServiceClass<Self, Identifier, Make extends Effect<_A, _E, _R> | (...args: _Args) => Effect<_A, _E, _R> ? _A : never> & {
    readonly make: Make;
  };
}

Service interface

Added in v4.0.0 Source

Context key with helper methods for working with a service.

Details

context creates a one-service Context, use and useSync retrieve the service from the current Effect context before applying a function, and of is a type-level helper for service values.

Signature

interface Service<in out Identifier, in out Shape> extends Key<Identifier, Shape> {
  context(self: Shape): Context<Identifier>;
  of(this: void, self: Shape): Shape;
  use<A, E, R>(f: (service: Shape) => Effect<A, E, R>): Effect<A, E, Identifier | R>;
  useSync<A>(f: (service: Shape) => A): Effect<A, never, Identifier>;
}

ServiceClass interface

Added in v4.0.0 Source

Class-style service key produced by Context.Service<Self, Shape>()("Id").

When to use

Use when declaring a service as a class so the class value can serve as the Context key.

Details

The class itself is the Context key, and its string key identifies the service at runtime.

See

  • Service for creating function-style keys or class-style service keys

Signature

interface ServiceClass<in out Self, in out Identifier extends string, in out Shape> extends Service<
  Self,
  Shape
> {
  constructor(_: never);
  readonly key: Identifier;
}

Type IDs

Runtime type identifier attached to Context service keys and used by isKey to recognize them.

Signature

declare const ServiceTypeId: "~effect/Context/Service";

ServiceTypeId type

Added in v4.0.0 Source

String literal type used as the runtime type identifier for Context service keys.

Signature

type ServiceTypeId = "~effect/Context/Service";

Unsafe

getUnsafe

Added in v4.0.0 Source

Gets the service for a key, throwing if an absent non-reference key cannot be resolved.

When to use

Use when you need to read a service from a context whose type does not prove the service is present.

Details

If the key is a Context.Reference and no override is stored in the context, its cached default value is returned. For absent non-reference keys, this function throws a runtime error.

See

  • get for type-checked service access
  • getOption for optional service access

Signature

declare const getUnsafe: {
  <S, I>(service: Key<I, S>): <Services>(self: Context<Services>) => S;
  <Services, S, I>(self: Context<Services>, services: Key<I, S>): S;
};