0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

react-reduxのstoreでのtype宣言を無くす

Last updated at Posted at 2020-05-04

ジェネリクスを完結にすることから始まりました。

react-reduxのuseSelectorする時いちいちジェネリクスを記述する雰囲気どうにかしたいな。。。
ググって先駆者を探していた所下記にたどり着きました。
react-redux の Hooks API に Generics は要らない

これで、ジェネリクスは記述する必要なくはなりました。

次なる問題、storeでのtype宣言が面倒臭い

今回はreducerから型を作り出して、DefaultRootStateにセットしてしまう試みです。

まず、declareを宣言して、StoreStateをreducerを元に生成します。

globals.d.ts
import { reducers } from "../stores";
import { Reducer } from "@reduxjs/toolkit";

type StoreState = {
  [key in keyof typeof reducers]: typeof reducers[key] extends Reducer<
    infer T,
    AnyAction
  >
    ? T
    : never;
};

declare module "react-redux" {
  interface DefaultRootState extends StoreState {}
}

そうすることで、storeが完結に書けるように。

store.ts
import { combineReducers } from "redux";
import { configureStore } from "@reduxjs/toolkit";
import "react-redux";
import reduxThunk from "redux-thunk";
import sliceReducer from "./slice";

export const reducers = {
  sliceReducer,
  // slice etc...
};

const reducer = combineReducers(reducers);
const store = configureStore({ reducer, middleware: [reduxThunk] });

export default store;
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?