我试图使用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>);
答案 0 :(得分:1)
解决方法是像这样简单地更改您的类型LStateHandlerProps
type LStateHandlerProps = {
reset: StateHandler<LStateProps>;
tick: StateHandler<LStateParops>;
setTimerId: StateHandler<LStateProps>;
} & StateHandlerMap<LStateProps>;
说明:如果将鼠标悬停在该状态的任何处理程序上,您将看到类似这样的函数类型
reset(state: LStateProps, props: TimerProps): () => StateHandler<LStateProps>
这种类型的问题是StateHandler<LStateProps>
的定义是一个函数
type StateHandler<TState> = (...payload: any[]) => Partial<TState> | undefined;
因此,这意味着reset
函数的类型不是双箭头,而是-与您的函数ex不匹配的三箭头。
reset: (state, props) => () => ({
...state,
timeLeft: props.limit,
})