The program is throwing an error stating that the property 'user' is not found on the data type 'DefaultRootState'

Issue Encounter

  • I am currently encountering the error message
    'user' does not exist on type 'DefaultRootState'.
    I have attempted to resolve it without success so far.

Here is the link to my GitHub repository.

Error Details

C:/Users/taiga/Github/Typescript/typescript-admin/admin/src/secure/components/Nav.tsx
TypeScript error in C:/Users/taiga/Github/Typescript/typescript-admin/admin/src/secure/components/Nav.tsx(44,50):
Property 'user' does not exist on type 'DefaultRootState'.  TS2339

File: Nav.tsx

class Nav extends Component<{ user: User }> {
  state = {
    redirect: false
  };

  handleClick = async () => {
    await axios.post('logout', {});

    this.setState({
      redirect: true
    });
  };

  render() {
    if (this.state.redirect) {
      return <Redirect to={'/login'} />;
    }

    return (
      <nav className="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
        <ul className="my-2 my-md-0 mr-md-3">
          <Link to={'/profile'} className="p-2 text-white">
            {this.props.user.name}
          </Link>
        </ul>
      </nav>
    );
  }
}

export default connect((state) => ({ user: state.user }))(Nav);

User Class Definition (user.ts)

mport { Role } from './role';

export class User {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  role: Role;
  permissions: string[];

  constructor(
    id = 0,
    first_name = '',
    last_name = '',
    email = '',
    role = new Role(),
    permissions: string[] = []
  ) {
    this.id = id;
    this.first_name = first_name;
    this.last_name = last_name;
    this.email = email;
    this.role = role;
    this.permissions = permissions;
  }

Redux Reducer for Setting User (setUserReducer.ts)

import { User } from '../../classes/user';

const setUserReducer = (
  state = { user: new User() },
  action: { type: string; user: User }
) => {
  switch (action.type) {
    case 'SET_USER':
      return {
        ...state,
        user: action.user
      };
    default:
      return state;
  }
};

export default setUserReducer;

Answer №1

An issue arises because the connect HOC is unaware of the specific type of your app's state, leading it to default to the generic type DefaultRootState, as defined in the react-redux types package.

To address this, one approach recommended by the types package is to override the definition of DefaultRootState with your actual state interface.

Users can augment this interface to incorporate default types for the root state when utilizing react-redux, employing module augmentation to append their own type definitions in a separate file such as 'your_custom_type.d.ts'. More details on module augmentation can be found at: here

Alternatively, a simpler solution involves explicitly declaring the expected state type within the mapStateToProps function.

export default connect((state: {user: User}) => ({ user: state.user }))(Nav);

By doing so, Typescript recognizes that your state should include a user property with the type User.

Another option is to specify the generic arguments on the connect function directly during its invocation, although the former method is generally preferred.

export default connect<{user: User}, {}, {}, {user: User}>((state) => ({ user: state.user }))(Nav);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for retrieving the selected option from a dropdown list using ReactJS

Currently, I am attempting to extract the value of a dropdown menu structured like this: <ul className="tabs" data-component={true}> <li> <section className="sort-list" data-component={true}> <select value={0} class ...

Centralize all form statuses in a single component, conveniently organized into separate tabs

I am working on a component that consists of 2 tabs, each containing a form: tab1.component.ts : ngOnInit() { this.params = getParameters(); } getParameters() { return { text : 'sample' form: { status: this.f ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

The 'current' in react typescript is not found within the type 'never'

Currently, I am working with react and typescript in my project. To fetch the height of a specific div tag, I decided to utilize useRef method. However, when trying to access 'current' property, TypeScript throws an error. Property 'current& ...

Quick way to specify type for Observable in Typescript

Exploring Shortcut Declarations When working with TypeScript, I often take a shortcut when declaring object shapes. Instead of creating an interface first and then specifying that the object conforms to that type, I simply do: object: { fizz: boolean, buz ...

No response was forthcoming

I have been trying to send a post request to my login endpoint, but I am not receiving any response. Despite thoroughly checking my code, I am unable to figure out why there is no response being sent back. My backend is built using Express in TypeScript. B ...

This error occurred: "Property 'release' cannot be read because it is undefined."

Hello everyone! I'm in need of some assistance. I am trying to test my service tree with a specific structure. Here is an overview of my test: describe(`Service selector`, () => { describe(`getCurrentServiceTree`, () => { it(`should bui ...

Converting a promise of type <any> to a promise of type <entity>: A beginner's guide

As a newcomer to TypeScript and NestJS, I am wondering how to convert Promise<any[]> to Promise<MyEntity[]> in order to successfully execute the following code: const usersfromTransaction = this.repoTransaction .createQueryBuilder() ...

Encountering issues with verifying login credentials in Angular 2

Greetings! I have designed a login page where the user will be logged in if the response is successful, otherwise an error message will be displayed. Below is the JSON data with email and password fields: { Email": "<a href="/cdn-cgi/l/email-protect ...

When attempting to compile my Angular project using the command ng build --prod, I encountered a server error stating that the document

Everything was running smoothly when I was working on my local machine, but once I uploaded the files generated from ng build --prod to the server, a problem arose. Now, whenever I try to route via a button in my components, an error appears. When I clic ...

Searching for client using mqtt.js in Angular2 with Typescript yields no results

I am facing a unique issue while trying to incorporate the mqtt.js library into Angular 2 using TypeScript. Below is my app.component.ts file: import { Component } from '@angular/core'; import * as mqtt from 'mqtt'; @Component({ sel ...

Expressions without a call signature cannot be invoked

When using an adapter in the given example, I encountered a type error specifically on the last line of the getGloryOfAnimal method. Despite having clearly defined types, I am puzzled by this issue. interface ICheetah { pace: string; } interface ILio ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Update state value with new data from Redux dispatch

My axios request is handled within the redux actions to ensure re-usability. However, I am facing an issue where I need to fetch data using redux and then update the state with the fetched data. Unfortunately, the data is not being populated in the state a ...

Issue with dependencies resolution in Nest framework

While delving into NestJS dependencies, I encountered an issue. As a beginner in learning Nest, I am still trying to grasp the correct way to structure everything. The problem lies in Nest's inability to resolve dependencies of the ChatGateway. It&a ...

What is the process for eliminating the perplexing "default" attribute that has been inserted into JSON?

I recently came across the jsondata.json file: { "name": "John", "age": 30, "car": "ferrari" } Located in the same directory is a typescript file called main.ts where I simply output the json data using console.log import * as j from '. ...

The defaultValue of the Observable TextArea is blank space following the transmission of a sendMessage using SignalR in a Typescript

i am currently in the process of modifying a basic SignalR Chat feature. Here is the situation: when a user sends a message, the message gets sent successfully. However, the textarea from which it was sent remains filled with empty space (aside from the p ...

The issue at hand is that the Mongo Atlas model is in place, but for some reason,

https://i.sstatic.net/4m2KT.pngI recently delved into using Next.js and I am a newcomer to backend technologies. I have successfully established a connection with MongoDB Atlas using Mongoose, however, the user object data from the post request is not be ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

What are the different types of class properties in TypeScript?

Currently, I am incorporating ES6 classes in typescript using the following code snippet: class Camera { constructor(ip) { this.ip = ip; } } Despite encountering an error message, it appears that the code still compiles successfully. The ...