javascript - 使用 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 抛出此错误的情况下使用该版本?
解决方案
推荐阅读
- css - 仅使用 css 隐藏选择选项
- json - 如何根据 Swift 中 JSON 的国家/地区在下拉列表中显示 statesList
- javascript - 打字稿正则表达式对象可能是“空”
- oracle - 在 Mybatis 的另一个结果 Map 中选择 List of Department as Collection
- sql - 如何避免多个连接以提取特定信息
- html - html公式苹果自动填充不起作用
- javascript - 如何制作带有过渡的水平滚动?
- ios - 我进入苹果签名按钮(使用 Apple 错误登录:Error Domain=com.apple.AuthenticationServices.AuthorizationError Code=1001 "(null)")?
- docker - Docker 在使用主机网络时无法绑定到 ipv4
- c++ - C ++写入帧缓冲区,错误的scrrensize