redux-toolkit & TypeScript

Goofi·2025년 2월 1일
0

기존 리액트 프로젝트에 타입스크립트 추가방법

npm i @types/node @types/react @types/react-dom @types/jest


타입스크립트는 기본적으로 JS 확장자 파일로 부터 JSX문법을 해석할 수 없다.

{
    "compilerOptions": {
        "target" : "ES5",
        "module" : "CommonJS",
        "strict" : true,
        "allowJs" : true
    },
    "include": ["src"]
}

allowJS jsx문법을 허용한 옵션

가져온 기본값이란 ESModule 시스템에서 default를 이용해서 내보낸 값이다.

해결방법 : default로 내보낸 값이 없더라도 그냥 모듈을 불러올 . 수있도록 컴파일러 오셥을 추가해주면 된다

"esModuleInterop": true tsconfig.json에 추가


타입스크립트 컴파일러는 기본적으로 jsx문법을 해석할 수 없다.
"jsx":"react-jsx"추가

document.getElementById('root')가 null타입을 반환할 수도 있다. 그렇기 때문에 createRoot는 null타입으로 인수를 받지 않기 때문에 에러가 발생하는것이다.

해결책 document.getElementById('root') as HTMLElement

redux-toolkit x TypeScript

import { configureStore } from '@reduxjs/toolkit'
// ...

export const store = configureStore({
  reducer: {
    posts: postsReducer,
    comments: commentsReducer,
    users: usersReducer,
  },
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch

업로드중..

✅ 결론
위와 같이 설정하면 TypeScript에서 Redux 상태를 더 안전하게 관리할 수 있어.
store.ts에서 RootState와 AppDispatch를 정의한 후, useSelector와 useDispatch에서 적용하면 돼! 🚀

profile
오늘보단 내일이 강한 개발자입니다!!🧑🏻‍💻

0개의 댓글