TypeScript has a potential to bring the following benefits to application:
- Type safety for state, stores and events
- Easy refactoring of typed code
- A superior developer experience in a team environment
A Practical Example
We will be going through a simplistic chat application to demonstrate a possible approach to include static typing. This chat application will have two domains. The Chat domain will focus on working with the chat history and the system domain will focus on working with session information.
The full source code is available on codesandbox here. Note that, by going through this example yourself, you will experience some of the benefits of using TypeScript.
Type checking state
Adding types to each slice of state is a good place to start since it does not rely on other types. In this example we start by describing the chat store's slice of state:
And then do the same for the system store's slice of state:
Note that we are exporting these interfaces to reuse them later in stores and events.
Organize your domains
To effectively structure the project code, you can break the application logic into separate domains that combine all the logic of working with this part of the application.
Type checking events and effects
All events can be typed through their payload. Effects used to handle async reactions and events for sync reactions.
Each effect must be provided with a handler function that will provide final processing. You can connect them at any time, so leave it for further action.
Type checking for stores
Keep yours stores as simple as possible. Let each store be responsible for its part of the state in the general state of the application or domain.
The closest comparison for an event handler is a reducer that processes exactly one event. In this example, there is no need to declare the types with which the handler will be called, since the typescript has enough information to deduce all the necessary types, it can also guarantee the correctness of the returned value from this handler.
While Effector React is a separate library from effector itself, it is commonly used with react. For this reason, we will go through how Effector React works with TypeScript using the same example used previously in this section.
Events and effects you can use directly in yours components and to get access
to store data you can use
useStore hook from
Let start with implement effect backend
Then bind created handlers to effects
Then we can implement components which uses data from stores. And start operating with our effects.
Also, close attention should be paid to the moment that the data from the local state can be transmitted to the final effect. For these purposes, the forward method is used. Here is an example of such use in the component.