0
0

[Redux] RootStateの型定義にはReturnTypeを使おうと思った話

Posted at

背景

Reduxを使用したアプリケーション開発時...
動的にstoreの型定義を行う方法があると知り記事化しました :pencil:

解説

storeReturnTypeを組み合わせることで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;

メリット

  1. 型安全性の向上: ReturnType を使用することで、ストアの状態に対する型推論が強化され、誤った型の使用や存在しないプロパティへのアクセスをコンパイル時に検出できる
  2. 保守性の向上: ストアの構造が変更された場合に、RootState の型定義を手動で更新する必要がなくなる

デメリット

  1. 初学者には理解しにくいかもしれない: 馴染みがないコードなのでTypeScriptの初学者にとっては少し理解しにくいかも

まとめ

1つのテクニックとして活用していきましょう :fire:

0
0
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
0