LoginSignup
3
4

More than 3 years have passed since last update.

【TypeScript】redux-observableでofTypeの型を完全に推論させる

Last updated at Posted at 2019-04-22

redux-observableの公式で提供されている型定義だとofTypeの推論ができないので、redux-observableの型定義を拡張してofTypeを推論させる方法について書きます。

ofTypeが推論されると、引数とofType後のActionがなんであるか確定し、payloadが補完されるようになるので便利です。

Image from Gyazo

Image from Gyazo

サンプルプロジェクト

サンプルプロジェクトを用意したので基本これの真似すればできます。
akameco/redux-observable-example
よかったらスターしてください。

How

では、解説していきます。

プロジェクトで一つのAction

redux-observableのofTypeで推論させるためにはまずプロジェクトで共通のAction型を定義する必要があります。Actionの型を定義する方法はたくさんありますが、このプロジェクトでは、as constredux-actions-type を使ってActionの型を定義します。

詳しくは、【redux】as constでaction creatorからActionの型を簡単につくる - Qiita を読んでください。

src/actionType.ts

import { ActionType } from "redux-actions-type";
import * as actions from "./actions";

export type Action = ActionType<typeof actions>;

redux-observableの型定義の拡張

Actionの型を利用し、redux-observableの型定義を拡張します。Action型が一つなので、Extractを使いofType引数から戻り値の型が推論されるようになります。

src/@types/redux-observable.d.ts

import { Action } from "../actionType";
import { Observable } from "rxjs";

declare module "redux-observable" {
  function ofType<ActionType extends Action["type"]>(
    ...key: ActionType[]
  ): (
    source: Observable<Action>
  ) => Observable<Extract<Action, { type: ActionType }>>;
}

Epic型の定義

最後にEpic型を定義しましょう。これを利用することでofTypeの推論が効くようになります。あとは、プロジェクトに合わせて必要であればStateやDependenciesを設定するとより補完が便利になるでしょう。

src/typeRoot.ts

import { Epic as _Epic } from "redux-observable";
import { Action } from "./actionType";

export type Epic = _Epic<Action, Action>;

Enjoy!

これで、ofType入力時の補完とofType後のActionが推論されるようになりました。
あとは補完が効く環境でEpicを書くだけです。Enjoy!

import { of } from "rxjs";
import { delay, mergeMap } from "rxjs/operators";
import { combineEpics, ofType } from "redux-observable";
import { Epic } from "../../typeRoot";
import { increment } from "./actions";

const incrementAsync: Epic = action$ =>
  action$.pipe(
    ofType("incrementAsync"),
    mergeMap(action => of(increment()).pipe(delay(action.delay)))
  );

akameco/redux-observable-example

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