首页 > 解决方案 > 使用 setState() 时出现“没有重载匹配此调用”TypeScript 错误

问题描述

当我编写以下代码时:

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 抛出此错误的情况下使用该版本?

标签: javascriptreactjstypescript

解决方案


推荐阅读