LoginSignup
3
4

More than 5 years have passed since last update.

flowtypeによるredux-thunkの型付け

Posted at

久しぶりにredux-thunkを使ってみたらflowの型定義が以前記事を書いたときと大きく変わっていました。

以前の記事。

flowtypeでredux-thunkの型定義を使う
http://qiita.com/akameco/items/5a0b427c1c5ef2967bac

flow-typedでインストールした型定義に後から手を入れるのちょっとやめたほうがいいかなという気持ちになりましたね。

今回は、types.js(もちろんファイル名は任意)以下に定義します。


// @flow
import type { Store as ReduxStore, Dispatch as ReduxDispatch } from 'redux'
import type { Action as _Action } from './action'
import type { State as _State } from './state'

export type State = _State
export type Action = _Action

type GetState = () => State

export type ThunkAction = (
  dispatch: Dispatch,
  getState: GetState,
) => void | Promise<void>
// ) => Action | Promise<Action>

type ThunkDispatch<A> = ThunkAction => A

export type Dispatch = ReduxDispatch<Action> & ThunkDispatch<Action>
export type Store = ReduxStore<State, Action>

本来ならdispatchはA => Aですけど、thunkでこれ許可するとカオスになるので、thunkの返り値はvoidで縛ってます。
しかし現状非同期dispatchなのか、同期dispatchなのか型でわからないのがちょっと嫌ですね。

しかしまあ、これで、以前のように定義されてないActionをDispatchしたら型エラーが起きます。(スクリーンショットはAtom-IDE)

スクリーンショット 2017-09-17 19.21.01.png

もっとうまく型付けできるなどの情報があればコメント欄もしくはtwitterまでよろしくお願いします。

3
4
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
3
4