LoginSignup
1
1

More than 1 year has passed since last update.

Redux Toolkit の store.ts をちゃんと理解する

Posted at

Redux Toolkit Quick Startを読みながら、Redux Toolkitを学習しているのですが、最初の store.ts の部分から、わからないところがあったので自分なりに調べてみました。


ReturnTypeとは何なのか?

app/store.ts

import { configureStore } from '@reduxjs/toolkit'

export const store = configureStore({
  reducer: {},
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch

 
ReturnTypesについては、【TypeScript】Utility TypesのReturnTypeを深く理解する では、以下のように説明されています。

ReturnTypeは、関数の戻り値の型から新たな型を生成します。

また、公式サイトを読むかぎり、ReturnTypesはTypeScriptの機能の一つのようです(Redux Toolkitの機能ではなかった!)。



ReturnTypesの使用例

公式サイトより

declare function f1(): { a: number; b: string };

type T0 = ReturnType<() => string>;  
// type T0 = string

type T1 = ReturnType<(s: string) => void>;     
// type T1 = void

type T2 = ReturnType<<T>() => T>;
// type T2 = unknown

type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
// type T3 = number[]

type T4 = ReturnType<typeof f1>;
/*     
type T4 = {
    a: number;
    b: string;
}
*/



したがって、上記のexport type RootState = ReturnType<typeof store.getState>は、

「storeコンポーネントに含まれる関数getStateの戻り値の型から、新しい型を作る」といった働きをします。



export type AppDispatchでは何をしているの?

export type AppDispatch = typeof store.dispatchでは、

1. `typeof store.dispatch`の部分で、ストアからDispatchの型を抽出
2. 抽出した型に対して`AppDispatch`という名前(エイリアス)をつける
3. 他のコンポーネントでも利用できるように`AppDispatch`をエクスポートする

といったことを行なっています。



参考

https://redux-toolkit.js.org/tutorials/quick-start
【TypeScript】Utility TypesのReturnTypeを深く理解する
https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype
https://redux-toolkit.js.org/usage/usage-with-typescript#using-the-extracted-dispatch-type-with-react-redux

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