[尝试更新react Component中的单状态属性时出现TS警告

问题描述 投票:0回答:1

假设我们有简单的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

我发现了一些可以解决此类警告的方法:

  1. IState替换为Partial<IState>
  2. 使所有IState项目为可选
interface IState {
  a: boolean;
  b: string;
  c: number;
}
  1. as IState添加this.setState({ a: false } as IState)
  2. 每次执行setState this.setState<'a'>({ a: false } as IState)时添加密钥名称
  3. 更新整个对象:
this.setState(prevState => ({
      ...prevState,
      a: false,
    }));

但是我想他们不是解决这个问题的好方法。那么,处理该恼人警告的最佳方法是什么?UPD:我发现仅在WebStorm中收到此警告。在CodeSandbox和VSCode中,没有警告

reactjs typescript setstate
1个回答
0
投票

Select TypeScript Language Service

问题已解决。只需确保选择了TypeScript Language Service

© www.soinside.com 2019 - 2024. All rights reserved.