Error encountered when using a connected component in Typescript with Redux

Seeking assistance on integrating state from redux into properties within a react component that is outlined in a tsx file.

The LoggedInUserState type has been defined elsewhere and is exported as shown below:

import { Action, Reducer } from 'redux';

// -----------------
// STATE - This defines the type of data maintained in the Redux store.

export interface LoggedInUserState {
    userName: string,
    isAdmin: boolean,
    isUserManager: boolean
}

This is the contents of my tsx file:

import * as React from 'react';
import { connect } from 'react-redux';
import { LoggedInUserState } from 'ClientApp/store/LoggedInUser';
import { NavLink } from 'react-router-dom';


export interface LinkProps {
    routeTo: string,
    name: string,
    glyphIcon: string
}

interface LoginStateProps {
    isAuthenticated: boolean
}

type ExpandedAuthProps =
    LinkProps & LoginStateProps;

class AuthenticatedLink extends React.Component<ExpandedAuthProps, null> {

    public render() {
        return this.props.isAuthenticated ?
            <NavLink exact to={this.props.routeTo} activeClassName='active'>
                <span className={this.props.glyphIcon}></span> {this.props.name}
            </NavLink> : 
            <NavLink exact to={'/loginUser'} activeClassName='active'>
                <span className='glyphicon glyphicon-ban-circle'></span> {this.props.name}
            </NavLink>;
    }
}

function mapStateToProps(state: LoggedInUserState, originalProps: LinkProps): ExpandedAuthProps {
    return {
        routeTo: originalProps.routeTo,
        name: originalProps.name,
        glyphIcon: originalProps.glyphIcon,
        isAuthenticated: state.userName != ''
    }
}

export default connect<LoggedInUserState, {}, LinkProps>
    (mapStateToProps)(AuthenticatedLink) as typeof AuthenticatedLink;

An error with typescript is being displayed at the end line regarding mapStateToProps:

Argument of type '(state: LoggedInUserState, originalProps: LinkProps) => ExpandedAuthProps' cannot be assigned to parameter of type 'MapStateToPropsParam'. Type '(state: LoggedInUserState, originalProps: LinkProps) => ExpandedAuthProps' is not assignable to type 'MapStateToPropsFactory'. Types of parameters 'originalProps' and 'ownProps' are incompatible. Type 'LinkProps | undefined' cannot be assigned to type 'LinkProps'. Type 'undefined' cannot be assigned to type 'LinkProps'.

What could be the issue with the declarations?

Answer №1

The error I am currently experiencing is different from the one you mentioned. When I compile this code, everything works perfectly:

export default connect(mapStateToProps)(AuthenticatedLink);

From what I understand about react-redux, it doesn't seem necessary to assert the result back to typeof AuthenticatedLink. The purpose of the connect function is to change the props type of the component from ExpandedAuthProps to LinkProps, as the LoginStateProps part is provided by the mapStateToProps function.

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

The resolver function in the Nextjs higher order API is not defined

I am trying to create a custom wrapper function for my NextJs API routes that will verify a JWT in the request, validate it, and then execute the original API handler. Here is how I have defined my wrapper function: interface ApiError { message: string, ...

Navigating directly to a page in ReactJS and Redux without needing to login if a token is found in the local storage

Currently in the main component, it is set to automatically redirect to the Login page. However, I want to implement a check to see if a token is already stored in the local storage. If a token exists, I want the application to skip the Login page and dire ...

When trying to compile FirebaseUI with typescript and react-redux, users may encounter issues

I'm attempting to implement firebaseui for a login feature in react-redux using typescript. Here is the code snippet: import firebase from 'firebase'; import firebaseui from 'firebaseui'; import fire from '../FirebaseCreds&ap ...

Is the array index a string or a number?

Why is it that when looping over the indexes of an array they appear as strings, even though using a string to index an array is not allowed? Isn't this inconsistency puzzling? for (const i in ["a", "b", "c"]) { console.log(typeof i + " " + i + " " ...

Transforming the window property in distinct entry points for TypeScript

During the initial page load, I am looking to transfer data from a template to a TypeScript file by attaching it to the window object. I want each page to utilize the same variable name for its specific data (window.data). An example of this can be seen in ...

Displaying notification in Ionic 2

Whenever I click on the register button, if I fill out all the fields I am taken to the regsuccess page. Otherwise, I receive a message saying to fill in all required fields. However, I want to display an alert message using Ionic2 and TypeScript. HTML: ...

Is it possible to create an observable with RXJS that emits only when the number of items currently emitted by the source observables matches?

I am dealing with two observables, obs1 and obs2, that continuously emit items without completing. I anticipate that both of them will emit the same number of items over time, but I cannot predict which one will emit first. I am in need of an observable th ...

Is there a more effective method to return a response apart from using a redundant function?

function unnecessaryFunction(){ let details: SignInDetails = { user: user, account: account, company: company }; return details; } I am being told that the details value is unnecessary. Is there ...

Unable to load class; unsure of origin for class labeled as 'cached'

Working on an Angular 10 project in visual studio code, I've encountered a strange issue. In the /app/_model/ folder, I have classes 'a', 'b', and 'c'. When running the application in MS Edge, I noticed that only classes ...

Stopping a build programmatically in Next.js involves implementing specific steps that aim to halt

Is there a method to programmatically halt the execution of npm run build in Next.js when a specific Error occurs within the getStaticProps function? Simply throwing an Error does not seem to stop the build process. ...

Definition for a function within a specific namespace that returns the specified object

Seeking to define the type of a function within a namespace (L.DomEvent.on(e)) that returns this, I encountered an issue with my JavaScript source code: L.DomEvent = { // @function on(el: HTMLElement, eventMap: Object, context?: Object): this on: ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

Error: While working in an Angular project, a TypeError occurs because the property '****' cannot be read when used within a forEach loop

As I attempt to iterate over this.data.members and perform certain actions within the forEach loop on this.addedUsers, I encounter a TypeError: Cannot read property 'addedUsers' of undefined. Interestingly, I can access this.data.members outside ...

How can the map function be executed sequentially every second, using async functions, fetch API, and promises, without running in parallel?

I am facing an issue with my map function, as it needs to fetch data from an online API that only allows one request per second. I attempted to solve this problem by implementing the following code: const sleep = (ms: number) => { return new Promise(( ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Encountered a problem while attempting to post in Angular, receiving an error message stating "net::ERR

I recently started learning Nodejs. I've created an API on a local server using Mysql and I'm working on the frontend with Angular, while using Nodejs and Express as the backend. However, I'm facing an issue where my Angular app cannot conne ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

Show varying mat-options based on the selected value of another mat-select

When selecting a continent from the first mat-select, only the countries belonging to that continent should appear in the second mat-select options. For example, if Asia is chosen as the continent, only Asian countries should be displayed. <div class=&q ...

Creating a versatile TypeScript Record that can accommodate multiple data types

I have a question regarding the use of Record in TypeScript. When I specify Record as the parameter type in a function, I encounter an error in my code because it does not allow different types. type Keys = 'name' | 'qty'; const getVal ...