LoginSignup
6
5

More than 5 years have passed since last update.

redux-observableをtypescriptで使いたい。

Last updated at Posted at 2017-07-15

RxJS自体はTypeScriptと相性は良いと思います。
RxJS自体がTypeScriptで作られているわけですし。

じゃあredux-observableはどうなんだろうとなりますが
意外とそうでもないです。
とくにofTypeがtypeScriptと相性が良くないです。
'typescript-fsa'がいい感じなので、対応してみました。

以下のコマンドでインストールします

yarn add typescript-fsa-redux-observable

使いかたはこんな感じ

import { State } from 'reducers';
import { Epic, combineEpics } from 'redux-observable';
import * as actions from '../actions';
import * as Rx from 'rxjs';
import 'typescript-fsa-redux-observable';


export const loadAccountEpic: Epic<{}, State> =
    (actions$, state) => actions$.ofAction(actions.loadAccount.started) 
        .mergeMap((action) => {
            return fetchAccount$(action.payload.accountID)
            .map(resp => actions.loadAccount.done({
                    params: {accountID: resp.id},
                    result: [resp]
            }))
            .catch(err => Rx.Observable.of(actions.loadAccount.failed({
                params: {accountID: 0},
                error: err
            })));
        });

epicを書く時にofTypeではなくofActionを使いactionCreatorを指定できます。
ofTypeのときとは違いactionの型を認識できるので前より楽になりました。

index_ts_—_taiya-ki-client.png

こんな感じで型がわかるわけです。

6
5
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
6
5