Action Helpers

부가설명
getType, isActionOf, isOfType, 타입비교
Tags
V4

Action Helpers

action-helpers가 뭔지, use-cases를 살펴보자.
 
사용자가 새로운 Todo를 추가했을 때 성공알림을 보여주는 사이드이펙트를 구현한다고 가정하자.
모든 helpertype-guard처럼 동작하므로, 태그가 지정된 유니언 유형(RootAction)으로부터 원하는 특정 action type으로 좁힐 수 있다.

[1] type-constants 대신 action-creators 인스턴스 사용

1) getType

  • reducers, epics 등에서 type-constants 대신 action-creators 인스턴스를 타입 비교 시에 활용할 수 있다.
  • type 문자열을 포함하고 있는 action-creator 인스턴스 앞에 static 프로퍼티만 추가하면 된다.
가장 대표적인 예시로는 리듀서switch-case에 유용한 getType이 있다.
import { getType } from 'typesafe-actions'; switch (action.type) { case getType(todos.add): // below action type is narrowed to: { type: "todos/ADD"; payload: Todo; } return [...state, action.payload]; ...

2) isActionOf

Then we have the isActionOf helper which accept action-creator as first parameter matching actions with corresponding type passed as second parameter (it's a curried function).
// epics.ts import { isActionOf } from 'typesafe-actions'; import { add } from './actions'; const addTodoToast: Epic<RootAction, RootAction, RootState, Services> = (action$, state$, { toastService }) => action$.pipe( filter(isActionOf(add)), tap(action => { // here action type is narrowed to: { type: "todos/ADD"; payload: Todo; } toastService.success(...); }) ... // Works with multiple actions! (with type-safety up to 5) action$.pipe( filter(isActionOf([add, toggle])) // here action type is narrowed to a smaller union: // { type: "todos/ADD"; payload: Todo; } | { type: "todos/TOGGLE"; payload: string; }
 

[2] type-constants 사용

그럼에도, 여전히 type-constants를 선호한다면 써도 된다.

3) isOfType

equivalent 여부 판별에 도움을 주는 isOfType helper도 있다.
  • type-constants를 매개변수로 받는다.
  • isActionOf 와 동일한 기능을 제공한다.
// epics.ts import { isOfType } from 'typesafe-actions'; import { ADD } from './constants'; const addTodoToast: Epic<RootAction, RootAction, RootState, Services> = (action$, state$, { toastService }) => action$.pipe( filter(isOfType(ADD)), tap(action => { // here action type is narrowed to: { type: "todos/ADD"; payload: Todo; } ... // Works with multiple actions! (with type-safety up to 5) action$.pipe( filter(isOfType([ADD, TOGGLE])) // here action type is narrowed to a smaller union: // { type: "todos/ADD"; payload: Todo; } | { type: "todos/TOGGLE"; payload: string; }

4) 팁 ( conditional statements )

💡
TIP: you can use action-helpers with other types of conditional statements. 다른 타입을 추가로 받아서 조건 판단에도 활용할 수 있다.
import { isActionOf, isOfType } from 'typesafe-actions'; if (isActionOf(actions.add, action)) { // here action is narrowed to: { type: "todos/ADD"; payload: Todo; } } // or with type constants if (isOfType(types.ADD, action)) { // here action is narrowed to: { type: "todos/ADD"; payload: Todo; } }