Using typed injections

Let's refactor our thunk from earlier so that the todosService is injected via our store.

Defining interface for injections

Firstly, let's define an interface to represent our injections.

// src/store/index.ts

import * as todosService from '../services/todos-service';

export interface Injections {
  todosService: typeof todosService;
}

Injecting into store

Now, let's update the code used to create our store.

// src/store/index.ts

const store = createStore(model, {
  // πŸ‘‡ provide injections to our store
  injections: { todosService }
});

Typing injections on our thunk

Then we will update the thunk definition on our model interface.

import { Injections } from '../store';
//          πŸ‘†import the injections type

export interface TodosModel {
  items: string[];
  addTodo: Action<TodosModel, string>;
  saveTodo: Thunk<TodosModel, string, Injections>; // πŸ‘ˆ provide the type
}

Refactoring thunk implementation to use injections

We can then refactor our thunk implementation.

const todosModel: TodosModel = {
  items: [],
  addTodo: action((state, payload) => {
    state.items.push(payload);
  }),
  saveTodo: thunk(async (actions, payload, { injections }) => {
    const { todosService } = injections; // πŸ‘ˆ destructure the injections
    await todosService.save(payload);
    actions.addTodo(payload);
  })
};

Again you should have noted all the typing information being available.

Typing info available using injections

Demo Application

You can view the progress of our demo application here