简体   繁体   中英

React & Redux tslint Warning

When I use react and redux. The connect method causes below tslint warning/error (I am not 100% sure about this statement too). Component works but looking at the tslint error is killing me.

type definition is this interface IPrivateMenuItem extends StateProps, IMenuItem, IOwnProps {}

Type '{ children: string; icon: "user"; to: string; }' is not assignable to type 'IntrinsicAttributes & Pick<IPrivateMenuItem, "hasAnyAuthorities" | "id" | "to" | "icon"> & IOwnProps'. Property 'children' does not exist on type 'IntrinsicAttributes & Pick<IPrivateMenuItem, "hasAnyAuthorities" | "id" | "to" | "icon"> & IOwnProps'.ts(2322)

I tried component definition like const PrivateMenuItem: React.FC<IPrivateMenuItem> . But no chance the warning gone. Unless I remove the connect statement. Which is not possible due to redux requirement.

Then, I switch the functional component's prop type to IPrivateMenuItem as defined below. Then the issue is gone. My question is if this is the best practice or is there an easier one?

interface IPrivateMenuItem extends StateProps, IMenuItem, React.PropsWithChildren<IOwnProps> {}

The full functional component code without imports is

interface IOwnProps {
  hasAnyAuthorities?: string[];
}

interface IPrivateMenuItem extends StateProps, IMenuItem, React.PropsWithChildren<IOwnProps> {}

const PrivateMenuItem = ({ isAuthorized, id, to, icon, children }: IPrivateMenuItem) => {
  return isAuthorized ? (
    <MenuItem id={id} to={to} icon={icon}>
      {children}
    </MenuItem>
  ) : (
    <></>
  );
};

const mapStateToProps = ({ authentication: { account } }: IRootState, { hasAnyAuthorities = [] }: IOwnProps) => ({
  isAuthorized: hasAnyAuthority(account.authorities, hasAnyAuthorities),
});

type StateProps = ReturnType<typeof mapStateToProps>;

export default connect(mapStateToProps)(PrivateMenuItem);

It's a bit hard without seeing the whole component but if it helps

The full typing for a connect is the following

connect<TheMapStateToPropsType, TheDispatchToPropsType, TheComponentPropsType, TheStorePropsType>

You can type you component like this: (I am doing it with a class but you get the spirit for a functional component )

interface OwnProps { }
interface StateProps { }
interface DispatchProps { }

type Props = OwnProps & StateProps & DispatchProps; 

export class MyComponent extends Component<Props> { } 

const mapStateToProps = (state): StateProps => ({ 
})

const mapDispatchToProps = (dispatch): DispatchProps => {
    return {
    }
}


export default connect<StateProps,DispatchProps,OwnProps,StorePropsIfYouWant>(mapStateToProps, mapDispatchToProps)(MyComponent)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM