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.
Demo Application
You can view the progress of our demo application here