当我编写以下代码时:
this.setState({ focus: true });
我收到此错误:
(property) State.focus: boolean
No overload matches this call.
Overload 1 of 2, '(f: (prevState: State, props: Props) => State, callback?: () => any): void', gave the following error.
Argument of type '{ focus: boolean; }' is not assignable to parameter of type '(prevState: State, props: Props) => State'.
Object literal may only specify known properties, and 'focus' does not exist in type '(prevState: State, props: Props) => State'.
Overload 2 of 2, '(state: State, callback?: () => any): void', gave the following error.
Argument of type '{ focus: true; }' is not assignable to parameter of type 'State'.
Property 'error' is missing in type '{ focus: true; }' but required in type 'State'.ts(2769)
StripeField.tsx(88, 3): 'error' is declared here.
我的状态如下:
this.state = {
focus: false,
error: ''
};
我的状态界面为:
interface State {
focus: boolean;
error: string;
}
当我将代码更改为以下内容时,上述错误消失了:
this.setState({ ...this.state, focus: true });
但是我的先前版本是有效的React代码,并且不太冗长。有没有一种方法可以使用该版本而不用TypeScript抛出此错误?