【问题标题】:How to resolve an error in Typescript about `withStateHandlers`如何解决 Typescript 中有关 `withStateHandlers` 的错误
【发布时间】:2019-07-10 13:06:29
【问题描述】:

我尝试使用 HOC 制作一个 React 示例应用程序。 但由于我在 Typescript 中遇到错误,我无法继续制作。

我在下面收到此错误消息

(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'.

你能告诉我如何解决它吗?

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>);

【问题讨论】:

标签: javascript reactjs higher-order-components recompose


【解决方案1】:

解决方法是像这样简单地更改您的类型LStateHandlerProps

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

说明:如果你将鼠标悬停在状态的任何处理程序上,你会看到这样的函数类型

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

而这种类型的问题在于StateHandler&lt;LStateProps&gt;的定义是一个函数

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

所以这意味着reset函数的类型不是双箭头,而是-与你的函数ex不匹配的三箭头

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

【讨论】:

    猜你喜欢
    • 2020-12-12
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2017-08-09
    相关资源
    最近更新 更多