Jieunny의 블로그

[TS] Redux-Toolkit 타입 설정하기 본문

Study/TypeScript

[TS] Redux-Toolkit 타입 설정하기

Jieunny 2023. 11. 3. 17:44

1. useDispatch, useSelector는 따로 hook 만들어서 사용하기

// hook.ts

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

export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

2. createAction 타입 설정하기(set 함수 매개변수 타입설정)

const setNaviValue = createAction<number>("naviValue/setNaviValue");
const setPopUp = createAction<boolean>("popUp/setPopUp");

3. state type 설정하기

type OwnState = {
  naviValue: number;
  popUp: boolean;
};

const initialState: OwnState = {
  naviValue: 0,
  popUp: false,
};

4. store 타입 export 해주기

export default store;
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;