Usage with TypeScript

TypeScript is a typed superset of JavaScript. It has become popular recently in applications due to the benefits it can bring. If you are new to TypeScript it is highly recommended to become familiar with it first before proceeding. You can check out its documentation here.

TypeScript has the potential to bring the following benefits to a Redux application:

  • Type safety for reducers, state and action creators
  • 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 reducers. The chat reducer will focus on storing the chat history and the system reducer will focus on storing 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 reducer's slice of state:

  1. // src/store/chat/types.ts
  2. export interface Message {
  3. user: string
  4. message: string
  5. timestamp: number
  6. }
  7. export interface ChatState {
  8. messages: Message[]
  9. }

And then do the same for the system reducer's slice of state:

  1. // src/store/system/types.ts
  2. export interface SystemState {
  3. loggedIn: boolean
  4. session: string
  5. userName: string
  6. }

Note that we are exporting these interfaces to reuse them later in reducers and action creators.

Type Checking Actions & Action Creators

We will be using string literals and using typeof to declare our action constants and infer types. Note that we are making a tradeoff here when we declare our types in a separate file. In exchange for separating our types into a separate file, we get to keep our other files more focused on their purpose. While this tradeoff can improve the maintainability of the codebase, it is perfectly fine to organize your project however you see fit.

Chat Action Constants & Shape:

  1. // src/store/chat/types.ts
  2. export const SEND_MESSAGE = 'SEND_MESSAGE'
  3. export const DELETE_MESSAGE = 'DELETE_MESSAGE'
  4. interface SendMessageAction {
  5. type: typeof SEND_MESSAGE
  6. payload: Message
  7. }
  8. interface DeleteMessageAction {
  9. type: typeof DELETE_MESSAGE
  10. meta: {
  11. timestamp: number
  12. }
  13. }
  14. export type ChatActionTypes = SendMessageAction | DeleteMessageAction

Note that we are using TypeScript's Union Type here to express all possible actions.

With these types declared we can now also type check chat's action creators. In this case we are taking advantage of TypeScript's inference:

  1. // src/store/chat/actions.ts
  2. import { Message, SEND_MESSAGE, DELETE_MESSAGE, ChatActionTypes } from './types'
  3. // TypeScript infers that this function is returning SendMessageAction
  4. export function sendMessage(newMessage: Message): ChatActionTypes {
  5. return {
  6. type: SEND_MESSAGE,
  7. payload: newMessage
  8. }
  9. }
  10. // TypeScript infers that this function is returning DeleteMessageAction
  11. export function deleteMessage(timestamp: number): ChatActionTypes {
  12. return {
  13. type: DELETE_MESSAGE,
  14. meta: {
  15. timestamp
  16. }
  17. }
  18. }

System Action Constants & Shape:

  1. // src/store/system/types.ts
  2. export const UPDATE_SESSION = 'UPDATE_SESSION'
  3. interface UpdateSessionAction {
  4. type: typeof UPDATE_SESSION
  5. payload: SystemState
  6. }
  7. export type SystemActionTypes = UpdateSessionAction

With these types we can now also type check system's action creators:

  1. // src/store/system/actions.ts
  2. import { SystemState, UPDATE_SESSION, SystemActionTypes } from './types'
  3. export function updateSession(newSession: SystemState): SystemActionTypes {
  4. return {
  5. type: UPDATE_SESSION,
  6. payload: newSession
  7. }
  8. }

Type Checking Reducers

Reducers are just pure functions that take the previous state, an action and then return the next state. In this example, we explicitly declare the type of actions this reducer will receive along with what it should return (the appropriate slice of state). With these additions TypeScript will give rich intellisense on the properties of our actions and state. In addition, we will also get errors when a certain case does not return the ChatState.

Type checked chat reducer:

  1. // src/store/chat/reducers.ts
  2. import {
  3. ChatState,
  4. ChatActions,
  5. ChatActionTypes,
  6. SEND_MESSAGE,
  7. DELETE_MESSAGE
  8. } from './types'
  9. const initialState: ChatState = {
  10. messages: []
  11. }
  12. export function chatReducer(
  13. state = initialState,
  14. action: ChatActionTypes
  15. ): ChatState {
  16. switch (action.type) {
  17. case SEND_MESSAGE:
  18. return {
  19. messages: [...state.messages, action.payload]
  20. }
  21. case DELETE_MESSAGE:
  22. return {
  23. messages: state.messages.filter(
  24. message => message.timestamp !== action.meta.timestamp
  25. )
  26. }
  27. default:
  28. return state
  29. }
  30. }

Type checked system reducer:

  1. // src/store/system/reducers.ts
  2. import {
  3. SystemActions,
  4. SystemState,
  5. SystemActionTypes,
  6. UPDATE_SESSION
  7. } from './types'
  8. const initialState: SystemState = {
  9. loggedIn: false,
  10. session: '',
  11. userName: ''
  12. }
  13. export function systemReducer(
  14. state = initialState,
  15. action: SystemActionTypes
  16. ): SystemState {
  17. switch (action.type) {
  18. case UPDATE_SESSION: {
  19. return {
  20. ...state,
  21. ...action.payload
  22. }
  23. }
  24. default:
  25. return state
  26. }
  27. }

We now need to generate the root reducer function, which is normally done using combineReducers. Note that we do not have to explicitly declare a new interface for AppState. We can use ReturnType to infer state shape from the rootReducer.

  1. // src/store/index.ts
  2. import { systemReducer } from './system/reducers'
  3. import { chatReducer } from './chat/reducers'
  4. const rootReducer = combineReducers({
  5. system: systemReducer,
  6. chat: chatReducer
  7. })
  8. export type AppState = ReturnType<typeof rootReducer>

Usage with React Redux

While React Redux is a separate library from redux itself, it is commonly used with react. For this reason, we will go through how React Redux works with TypeScript using the same example used previously in this section.

Note: React Redux does not have type checking by itself, you will have to install @types/react-redux by running npm i @types/react-redux -D.

We will now add type checking to the parameter that mapStateToProps receives. Luckily, we have already declared what the store should look like from defining a type that infers from the rootReducer:

  1. // src/App.tsx
  2. import { AppState } from './store'
  3. const mapStateToProps = (state: AppState) => ({
  4. system: state.system,
  5. chat: state.chat
  6. })

In this example we declared two different properties in mapStateToProps. To type check these properties, we will create an interface with the appropriate slices of state:

  1. // src/App.tsx
  2. import { SystemState } from './store/system/types'
  3. import { ChatState } from './store/chat/types'
  4. interface AppProps {
  5. chat: ChatState
  6. system: SystemState
  7. }

We can now use this interface to specify what props the appropriate component will receive like so:

  1. // src/App.tsx
  2. class App extends React.Component<AppProps> {

In this component we are also mapping action creators to be available in the component's props. In the same AppProps interface we will use the powerful typeof feature to let TypeScript know what our action creators expect like so:

  1. // src/App.tsx
  2. import { SystemState } from './store/system/types'
  3. import { updateSession } from './store/system/actions'
  4. import { ChatState } from './store/chat/types'
  5. import { sendMessage } from './store/chat/actions'
  6. interface AppProps {
  7. sendMessage: typeof sendMessage
  8. updateSession: typeof updateSession
  9. chat: ChatState
  10. system: SystemState
  11. }

With these additions made props that come from redux's side are now being type checked. Feel free to extend the interface as necessary to account for additional props being passed down from parent components.

Usage with Redux Thunk

Redux Thunk is a commonly used middleware for asynchronous orchestration. Feel free to check out its documentation here. A thunk is a function that returns another function that takes parameters dispatch and getState. Redux Thunk has a built in type ThunkAction which we can utilize like so:

  1. // src/thunks.ts
  2. import { Action } from 'redux'
  3. import { sendMessage } from './store/chat/actions'
  4. import { AppState } from './store'
  5. import { ThunkAction } from 'redux-thunk'
  6. export const thunkSendMessage = (
  7. message: string
  8. ): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
  9. const asyncResp = await exampleAPI()
  10. dispatch(
  11. sendMessage({
  12. message,
  13. user: asyncResp,
  14. timestamp: new Date().getTime()
  15. })
  16. )
  17. }
  18. function exampleAPI() {
  19. return Promise.resolve('Async Chat Bot')
  20. }

It is highly recommended to use action creators in your dispatch since we can reuse the work that has been to type check these functions.

Notes & Considerations

  • This documentation covers primarily the redux side of type checking. For demonstration purposes, the codesandbox example also uses react with React Redux to demonstrate an integration.
  • There are multiple approaches to type checking redux, this is just one of many approaches.
  • This example only serves the purpose of showing this approach, meaning other advanced concepts have been stripped out to keep things simple. If you are code splitting your redux take a look at this post.
  • Understand that TypeScript does have its trade-offs. It is a good idea to understand when these trade-offs are worth it in your application.