Home > Blockchain >  Object is of type 'unknown'.ts
Object is of type 'unknown'.ts

Time:06-19

I'm trying TypeScript by creating a Redux store with Redux Tooklit.

Here is my redux.js file :

import { configureStore, createSlice } from "@reduxjs/toolkit";

const testSlice = createSlice({
  name: "test",
  initialState: [],
  reducers: {
    callApi: (state, action) => {
      const getData = {
        type: "test/getData",
        data: action.payload
      };

      state.push(getData);
    }
  }
});

export const store = configureStore({
  reducer: {
    test: testSlice.reducer
  }
})

Here is my index.tsx file :

import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import App from './App';
import './index.css';
import { store } from './redux'

const container = document.getElementById('root')!;
const root = createRoot(container);

root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

And finaly, my component Login.tsx file :

[...]
import { useSelector } from 'react-redux';

[...]
const test = useSelector((state) => state.test);
[...]

In Login.tsx, VSCode underline state in red, and says :

Object is of type 'unknown'

I tried to tell TypeScript what kind of type to expect like this : const test = useSelector((state: Object) => state.test); but I get an error saying that test is not an object. Same try with Array.

I'm a bit lost. Can anyone explain me where is my mistake and how to fix this ?

Thank you very much.

CodePudding user response:

You can add this line od code to redux.js file

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

Then you can use this type in useSelector hook

const test = useSelector((state: RootState) => state.test);

CodePudding user response:

As you are correctly thinking you need to give a type to the state so that it doesn't get the default unknown type. However, instead of using the Object type you should use a custom one that correctly represents your whole state. You can create one by adding this in your redux.js file:

export type RootState = ReturnType<typeof store.getState>

Then, from your Login.tsx file you can do:

const test = useSelector((state: RootState) => state.test);

More official docs here: https://redux-toolkit.js.org/tutorials/quick-start#add-slice-reducers-to-the-store

  • Related