Choose runtime structure and behavior

Dependency Injection in TypeScript Without Classes or a Container

Build a function-based TypeScript order service with explicit dependencies, application wiring, and tests for call order and failure.

Editorial illustration for Dependency Injection in TypeScript Without Classes or a Container

If an order service needs to charge a payment and save an order, it does not need to know where those functions come from. Give it the functions when you create it. That is dependency injection without a class or a container: the caller selects the dependencies, and the service uses them.

This is the function-based counterpart to passing dependencies into a class constructor. The useful question is not which injection tool to install, but what the service actually needs. A function can receive a dependency explicitly, as in this example that accepts a replaceable random-number function.

Define the service’s dependency boundary

Put the order shape, dependency shapes, and factory together in order-service.ts. Both operations are asynchronous, and placeOrder waits for charging to finish before it asks to save.

// order-service.ts
export type Order = {
  id: string;
  totalCents: number;
};

export type OrderDependencies = {
  charge: (order: Order) => Promise<void>;
  save: (order: Order) => Promise<void>;
};

export function createOrderService({ charge, save }: OrderDependencies) {
  return async function placeOrder(order: Order): Promise<void> {
    await charge(order);
    await save(order);
  };
}

The boundary says what the service calls, not how payments or storage work. It also makes the failure path apparent: if charge rejects, execution does not reach save. The service does not catch that rejection or claim that the order was saved.

An object is handy here because the two functions have different jobs and named properties make wiring readable. For a service with only one dependency, a single function parameter may be clearer. Neither choice requires a class. Class-based examples use the same separation between a dependency contract and its implementation; a constructor-injected logger example illustrates that distinction.

Select implementations at the application edge

The application, rather than order-service.ts, decides what to pass. This standalone app.ts uses in-memory adapter functions to make the wiring concrete. They record IDs and orders; they do not contact a payment provider or a database.

// app.ts
import {
  createOrderService,
  type Order,
} from "./order-service";

const chargedIds: string[] = [];
const savedOrders: Order[] = [];

async function chargePayment(order: Order): Promise<void> {
  chargedIds.push(order.id);
}

async function persistOrder(order: Order): Promise<void> {
  savedOrders.push(order);
}

export const placeOrder = createOrderService({
  charge: chargePayment,
  save: persistOrder,
});

In an application with payment and persistence adapters, this is the place to select those functions instead. The service itself need not import them or choose between implementations. Explicit wiring is a reasonable starting point for a small dependency graph; a container can automate more extensive wiring, but it is not needed to pass these two functions. See the manual wiring discussion for the same composition-at-the-edge idea in a class-based example.

With these typed definitions, the checker can assess whether the functions passed to createOrderService have the required signatures. For example, a function requiring a number instead of an Order does not satisfy the declared charge dependency:

// Deliberately invalid: the parameter does not match Order.
createOrderService({
  charge: async (amount: number): Promise<void> => {},
  save: persistOrder,
});

That is a static compatibility check, not proof that chargePayment charges anyone or that persistOrder stores anything durable.

Test the sequence with fakes

A fake can record what the service attempted without invoking either application adapter. The following framework-independent check is an async function: call or await it from a test runner that reports a thrown error or rejection as a failure.

// order-service.check.ts
import {
  createOrderService,
  type Order,
} from "./order-service";

function assert(condition: boolean, message: string): void {
  if (!condition) throw new Error(message);
}

export async function checkOrderService(): Promise<void> {
  const order: Order = { id: "order-1", totalCents: 1200 };
  const calls: string[] = [];

  const placeOrder = createOrderService({
    charge: async (_order: Order): Promise<void> => {
      calls.push("charge");
    },
    save: async (_order: Order): Promise<void> => {
      calls.push("save");
    },
  });

  await placeOrder(order);
  assert(calls.join(",") === "charge,save", "expected charge before save");

  const failedCalls: string[] = [];
  const placeOrderWithFailure = createOrderService({
    charge: async (_order: Order): Promise<void> => {
      failedCalls.push("charge");
      throw new Error("charge rejected");
    },
    save: async (_order: Order): Promise<void> => {
      failedCalls.push("save");
    },
  });

  let rejected = false;
  try {
    await placeOrderWithFailure(order);
  } catch {
    rejected = true;
  }

  assert(rejected, "expected the charge failure to propagate");
  assert(failedCalls.join(",") === "charge", "save must be skipped");
}

These checks exercise the service’s sequencing and rejection path with the supplied fakes. They do not test a real payment request, a database write, or what happens if saving fails. Receiving dependencies is what makes that substitution possible; the testing discussion here describes the same benefit for classes.

Finally, keep the runtime boundary in view. TypeScript types and interfaces do not remain in compiled JavaScript, as this discussion of runtime dependency tokens notes. The Order annotation does not validate an order arriving from a request. Check untrusted data before calling placeOrder; use the dependency types to describe the functions your already-checked code passes around.

Find a note

Search by topic, title, or keyword.