3

I have a configured project with React, Redux, Immutable.js + TypeScript. During implementation I was trying to declare types as much as possible and found interesting issue. See code example below:

Short configuration of redux store

import { createStore } from 'redux';
import { combineReducers } from 'redux-immutable';

const rootReducer = combineReducers({...});
const store = createStore(rootReducer);

Somewhere inside component

// ...
const mapStateToProps = (state: ReturnType<typeof rootReducer>) => {
  // state is plain object :(
};

On state hover in VS Code, tooltip shows that state is a plain object, however it is not. It should be a custom collection from Immutable.js

How can I get a correct type of rootReducer? Or what I am doing wrong?

Screenshots:

Hovered mouse over state variable

Hovered mouse over emphasized get method

P.S. StateType and ReturnType do the same stuff

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68

2 Answers2

1

This works (no need for Immutable.js):

export type RootState = ReturnType<typeof rootReducer>;

If for some reason it does not works, this one should work:

export type RootState = ReturnType<typeof store.getState>
0

I spent a lot of time on finding a solution of how to make TypeScript work with Immutable.js in pair and unfortunately there is no explicit/trivial solution (or I didn't find it).

If you on the start of your project and looking for some alternatives I would highly recommend you to take a look at the Immer library. It provides mostly the same functionality and perfectly supports TypeScript typings.

Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68