Effect CommunityEC
Effect Community3y ago
115 replies
Stephen Bluck

Exploring Services and Context for Dependency Injection in TypeScript

I am playing around with Services and Context - I am trying to find a way where I don't have to pass in the R when defining the interface. I am finding it odd that I have to define the dependencies up front for a service that could have a variety of different implementations with each one requiring different deps. I am new to Effect. Is it even possible?

interface RandomNumber<R = never> {
  make: Effect.Effect<R, never, number>;
}

class MattsRandomNumber implements RandomNumber<SomeDep> {
  make = Effect.gen(function* ($) {
    const dep = yield* $(SomeDep);
    return dep.a.length;
  });
}

type SomeDep = { a: string };

const SomeDep = Context.Tag<SomeDep>();
const RandomNumber = Context.Tag<RandomNumber>();

const context = pipe(
  Context.empty(),
  Context.add(SomeDep, { a: 'asdasdad' }),
  Context.add(RandomNumber, new MattsRandomNumber()) // Type 'SomeDep' is not assignable to type 'never'
);


const program = pipe(
  RandomNumber,
  Effect.flatMap((randomString) => randomString.make),
  Effect.provideContext(context)
);
Was this page helpful?