how to solve this error: Property 'detailNew' does not exist on type 'DefaultRootState'?

Viewed 34

I get this error and I don't know how to fix it, I'm new to using typescript TypeScript error in /projects/app-colegiado/packages/client/src/components/news/NewsDetail.tsx(6,54): Property 'detailNew' does not exist on type 'DefaultRootState'.?

import { combineReducers } from 'redux'
import { detailNewReducer }  from './detailNewReducer'

const rootReducer = combineReducers({
  detailNew: detailNewReducer
})

export default rootReducer
import detailNewActionTypes from "../constants/actionTypes";

export const detailNewReducer = (item = {}, action) => {
  switch (action.type) {
    case detailNewActionTypes.ADD_NEW_DETAIL:
      return  { 
        title: action.item.title, 
        creationDate: action.item.creationDate, 
        id: action.item.id,
      };

     
    default:
      return item;
  }
}
import React from 'react';
import { useSelector } from "react-redux";

export const NewsDetail = () => {

    const detailsItem = useSelector((state) => state.detailNew);

    return(
        <>
            <div >
                <img src="#" alt="#">{}</img>
            </div>
            <div>{detailsItem.creationDate}</div>
            <div>{detailsItem.title }</div>
            
        </>
    )
}
1 Answers

You have to tell the useSelector hook what the type of the state parameter is. useSelector is created by calling createSelectorHook, which is defined as:

export function createSelectorHook(
  context = ReactReduxContext
): <TState = unknown, Selected = unknown>(
  selector: (state: TState) => Selected,
  equalityFn?: EqualityFn<Selected>
) => {
  // ...
}

So as you can see, if you don't specify your state type, it will be unknown, which is why you get the error.

The easiset thing to do is to declare your RootState type to be the return type produced by running the getState on your redux store:

// Wherever your store is configured...
export const store = configureStore({
  reducer: rootReducer,
});

// Add this!
export type RootState = ReturnType<typeof store.getState>;

Now you can import and use the RootState type:

import type { RootState } from 'core/store';  // Or wherever your store is

export const NewsDetail = () => {
  const detailsItem = useSelector((state: RootState) => state.detailNew);

  // ...
};
Related