背景
Reduxを使用したアプリケーション開発時...
動的にstore
の型定義を行う方法があると知り記事化しました
解説
store
と ReturnType
を組み合わせることでRootState
の型を動的に定義することができます。
-
store
: Reduxのグローバル値を管理 -
ReturnType
: 関数の戻り値の型から新たな型を生成
以下の例では、複数のリデューサーを含むstore
を設定し、store.getState
の戻り値からRootState
の型を動的に定義しています。
// src/stores/index.ts
import { configureStore } from '@reduxjs/toolkit';
import hogeSlice from './hoge';
import fooSlice from './foo';
const store = configureStore({
reducer: {
hoge: hogeSlice.reducer,
foo: fooSlice.reducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export default store;
メリット
-
型安全性の向上:
ReturnType
を使用することで、ストアの状態に対する型推論が強化され、誤った型の使用や存在しないプロパティへのアクセスをコンパイル時に検出できる -
保守性の向上: ストアの構造が変更された場合に、
RootState
の型定義を手動で更新する必要がなくなる
デメリット
- 初学者には理解しにくいかもしれない: 馴染みがないコードなのでTypeScriptの初学者にとっては少し理解しにくいかも
まとめ
1つのテクニックとして活用していきましょう