Redux + Typescript 초기 설정

shleecloud·2022년 4월 10일
0

들어가며

Typescript를 본격적으로 사용하는 작업은 처음이다. 그러다보니 초기 설정 같은 부분은 건너뛰고 곧바로 작업에 들어갔다. Typescript를 적용하면 타입을 지정하지 않는 경우 any로 판단해서 실행이 아예 안되지는 않지만 경고 메세지가 계속 나온다. 특히 Redux 환경에서 useSelector useDispatch 사용할 때 유독 발생했다.

@types/react-redux

패키지도 typed 가 앞에 붙은 패키지를 설치해야된다. v7.3.2 부터 기본적으로 설치가 된다고 하지만 더 명시적으로 하려면 이렇게 설치하는게 좋다.

Define Root State and Dispatch Types

에러 메세지에 RootState를 달라고 계속 뜨게된다. 이 타입 값은 store 만드는 과정에서 뽑을 수 있다.
typeof store.getState 여기서 getState 명령어는 Js 환경에서 리덕스 스토어에 접근하는 명령어다. 여기서 ReturnType 함수로 타입을 추출한다.

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import ReduxThunk from 'redux-thunk';
import rootReducer from './rootReducer';

export const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(ReduxThunk)));
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

Define Typed Hooks

useSelector , useDispatch 둘 다 타입이 필요하다. 그래서 별도의 파일에서 해당 함수를 타입을 지정한 함수로 새롭게 정의하고 그 함수를 사용한다. 그러면 자동으로 타입이 붙어나가면서 에러 메세지가 사라지게 된다. 이 외에도 사용할때마다 타입을 지정하는 방법이 있는데 매번 번거롭기 때문에 이 방법을 추천한다.

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
import type { RootState, AppDispatch } from './store'

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

참고 URL

profile
블로그 옮겼습니다. https://shlee.cloud

0개의 댓글