简体   繁体   中英

How to resolve an error in Typescript about `withStateHandlers`

I tried to make a React sample application using HOC. but since I got an error in Typescript, I couldn't keep making anymore.

I got this error message below

(34,38): Type '{ timeLeft: number; timerId?: Timer | undefined; }' is not assignable to type 'StateHandler<LStateProps>'.
  Type '{ timeLeft: number; timerId?: Timer | undefined; }' provides no match for the signature '(...payload: any[]): Partial<LStateProps> | undefined'.

Could you please tell me how to resolve it?

import * as React from 'react';
import {
  compose,
  StateHandler,
  StateHandlerMap,
  withStateHandlers,
} from 'recompose';

import Timer, { TimerProps } from 'components/Timer';

interface LStateProps {
  timeLeft: number;
  timerId?: NodeJS.Timer;
}

type LStateHandlerProps = {
  reset: () => StateHandler<LStateProps>;
  tick: () => StateHandler<LStateProps>;
  setTimerId: (timerId: NodeJS.Timer) => StateHandler<LStateProps>;
} & StateHandlerMap<LStateProps>;

type EnhancedTimerProps = TimerProps & LStateProps & LStateHandlerProps;

const enhance = compose<EnhancedTimerProps, TimerProps>(
  withStateHandlers<LStateProps, LStateHandlerProps, TimerProps>(
    props => ({
      timeLeft: props.limit,
    }),
    {
      reset: (state, props) => () => ({
        ...state,
        timeLeft: props.limit,
      }),
      tick: (state, props) => () => ({
        ...state,
        timeLeft: state.timeLeft - 1,
      }),
      setTimerId: (state, props) => (timerId: NodeJS.Timer) => ({
        ...state,
        timerId,
      }),
    },
  ),
);

export default enhance(Timer as React.SFC<EnhancedTimerProps>);

The workaround is to simply change your type LStateHandlerProps like this

type LStateHandlerProps = {
  reset: StateHandler<LStateProps>;
  tick: StateHandler<LStateParops>;
  setTimerId: StateHandler<LStateProps>;
} & StateHandlerMap<LStateProps>;

Explanation: if you hover your mouse to any handler of the state, you will see the type of the function like this

reset(state: LStateProps, props: TimerProps): () => StateHandler<LStateProps>

and the problem with this type is that the definition of StateHandler<LStateProps> is a function

type StateHandler<TState> = (...payload: any[]) => Partial<TState> | undefined;

So it means that the type of reset function is not double arrow, but instead - triple arrow that is not matching your function ex

 reset: (state, props) => () => ({
     ...state,
     timeLeft: props.limit,
 })

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