Home > database >  (parameter) state: unknown Object is of type 'unknown'. redux TS
(parameter) state: unknown Object is of type 'unknown'. redux TS

Time:04-29

const submitted = useSelector((state) => state.post.submitted)

For above at state. I get error:

(parameter) state: unknown Object is of type 'unknown'.

How is this fixed?

I have simple slice store:

import { createSlice } from '@reduxjs/toolkit'

export const postSlice = createSlice({
  name: 'post',
  initialState: {
    shared: false,
    submitted: false,
  },
  reducers: {
    setShared: (state, action) => {
      state.shared = action.payload
    },
    setSubmitted: (state, action) => {
      state.submitted = action.payload
    },
  },
})

export const { setShared, setSubmitted } = postSlice.actions
export default postSlice.reducer

import { configureStore, combineReducers } from '@reduxjs/toolkit'

//import slice as reducer
import postReducer from './features/postSlice'

const rootReducer = combineReducers({
  //combine all reducers
  post: postReducer,
})

export const store = configureStore({
  reducer: rootReducer,
})

I don't get this type of error on Javascript, though pops up in TS? Wat type of types need to be declared for this if needed?

CodePudding user response:

useSelector is a generic and can't determine what type state is, so defaults to unknown. You need to give state a type annotation which matches the shape of initialState, so you'll need to break that out of the slice definition.

  1. Define the interface (or use a type/type alias if you prefer)
interface MyState {
  shared: boolean
  submitted: boolean
}
  1. Type cast the initialState, or use an intermediate typed variable (I think this is optional but a look at the documented examples suggests this is possible):
  // ...
  initialState: {
    shared: false,
    submitted: false,
  } as MyState,
  // ...
  1. Add a type annotation to the callback
const submitted = useSelector((state: MyState) => state.post.submitted)

CodePudding user response:

You should follow the TypeScript QuickStart guide and set up correctly typed hooks:

// store.ts

// 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
//hooks.ts

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
  • Related