LoginSignup
13
8

More than 3 years have passed since last update.

TypeScript で Redux DevTools extension を使う

Last updated at Posted at 2019-10-22

公式のJS向けコードをそのまま持ってくると Property '__REDUX_DEVTOOLS_EXTENSION_COMPOSE__' does not exist on type 'Window'. TS2339 とコンパイラに怒られてしまう。

そこで、 window__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ を持つこと、およびその型を明示的にコンパイラに伝える必要がある。

以下の型定義を ts ファイル中に書くだけでいい。

partial.ts
interface ExtendedWindow extends Window {
  __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
}
declare var window: ExtendedWindow;

全体としては以下のような形。

store.ts
import {
  createStore,
  applyMiddleware,
  compose,
} from "redux";

interface ExtendedWindow extends Window {
  __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
}
declare var window: ExtendedWindow;

const composeReduxDevToolsEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// TODO: 適宜ミドルウェア定義、本記事とは関係ないので割愛
const middlewares = [];

const store = createStore(
  initReducer(),
  state,
  composeReduxDevToolsEnhancers(applyMiddleware(...middlewares))
);
13
8
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
13
8