본문 바로가기
React/TS

React에서 TypeScript 사용하기 - Redux with typesafe-actions

by 강깅꽁 2020. 10. 26.

TS 사용하지 않고 redux module 코드를 작성할 때는 유틸 함수인 redux-actions 라이브러리를 사용했습니다.

action creator나 reducer를 작성할 때 코드의 가독성을 올려줄 뿐만 아니라 코드를 작성하기 편리했습니다.

typesafe-actions도 이러한 유틸 라이브러리인데 TS를 지원해줍니다.

 

먼저 redux-actions를 사용한 redux module의 코드는 다음과 같습니다.

import { createAction, handleActions } from "redux-actions"

const INCREASE = "counter/INCREASE"
const DECREASE = "counter/DECREASE"

export const increase = createAction(INCREASE, num => num)
export const decrease = createAction(DECREASE, num => num)

const initialState = {
  count: 0,
}

const counter = handleActions(
  {
    [INCREASE]: (state, action) => ({ count: state.count + action.payload }),
    [DECREASE]: (state, action) => ({ count: state.count - action.payload }),
  },
  initialState
)

export default counter

 

위의 코드를 typesafe-actions를 사용하면 다음과 같습니다.

reducer 파라미터로 들어가는 state와 action들의 타입이 필요한데 action type의 경우

ActionType 유틸 타입을 사용합니다.

ActionType은 action creator map object를 통해서 액션들의 타입을 추론해주는 유틸 타입입니다.

createReducer의 경우 제네릭으로 상태의 타입 그리고 액션의 타입을 타입 파라미터로 가집니다. 

 

import { ActionType, createAction, createReducer} from 'typesafe-actions';

const INCREASE = 'counter/INCREASE';
const DECREASE = 'counter/DECREASE';

export const increase = createAction(INCREASE, (num: number) => num)();
export const decrease = createAction(DECREASE, (num: number) => num)();

type CounterState = {
    count: number;
}

const initialState: CounterState = {
    count: 0,
}

const actions = {increase, decrease};
type CounterAction = ActionType<typeof actions>;

const counter = createReducer<CounterState, CounterAction>(initialState, {
    [INCREASE]: (state, action) => ({ count: state.count + action.payload}),
    [DECREASE]: (state, action) => ({ count: state.count - action.payload}),
})

export default counter;

 

공식 가이드

github.com/piotrwitek/typesafe-actions#actiontype