假设我们有简单的react组件:
import React, { Component } from 'react';
interface IState {
a: boolean;
b: string;
c: number;
}
class Test extends Component<{}, IState> {
state = {
a: true,
b: 'value',
c: 7,
};
handleClick = () => {
this.setState({ a: false });
};
render() {
const { a, b, c } = this.state;
return (
<div>
{a && b + c}
<button onClick={this.handleClick}>Click</button>
</div>
);
}
}
export default Test;
CodeSandbox:https://codesandbox.io/s/confident-shirley-zlxib?fontsize=14&hidenavigation=1&theme=dark
但是我收到此消息:
Argument type {a: boolean} is not assignable to parameter type ((prevState: Readonly<IState>, props: Readonly<{}>) => (Pick<IState, keyof IState> | IState | null)) | Pick<IState, keyof IState> | IState | null
我发现了一些可以解决此类警告的方法:
IState
替换为Partial<IState>
IState
项目为可选interface IState {
a: boolean;
b: string;
c: number;
}
as IState
添加this.setState({ a: false } as IState)
setState
this.setState<'a'>({ a: false } as IState)
时添加密钥名称this.setState(prevState => ({
...prevState,
a: false,
}));
但是我想他们不是解决这个问题的好方法。那么,处理该恼人警告的最佳方法是什么?UPD:我发现仅在WebStorm中收到此警告。在CodeSandbox和VSCode中,没有警告
Select TypeScript Language Service
问题已解决。只需确保选择了TypeScript Language Service
。