首页 > 解决方案 > 我无法在打字稿中使用动态键名设置状态

问题描述

我定义了 React 组件的状态接口如下。

interface IState {
    email: string,
    password: string,
    errors: object
}

在文本输入更改事件中,我尝试使用如下动态键设置状态。

handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {

        this.setState({
            [e.target.name]: e.target.value
        });
    }

但是 VSCode 向我显示了这个错误

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'IState | ((prevState: Readonly<IState>, props: Readonly<{}>) => IState | Pick<IState, "email" | "password" | "errors"> | null) | Pick<IState, "email" | "password" | "errors"> | null'.
  Type '{ [x: string]: string; }' is missing the following properties from type 'Pick<IState, "email" | "password" | "errors">': email, password, errorsts(2345)

任何的建议都受欢迎。

标签: reactjstypescript

解决方案


问题是它e.target.name应该是 key ofIState并且e.target.value应该是 key in 的相对类型IState,要修复它,您可以手动转换类型,例如

this.setState({
            [e.target.name]: e.target.value
    } as Pick<IState, keyof IState>);

但它禁用了这个函数的打字稿,你也可以将它转换为任何类型,但它是不安全的。

看起来这个答案对你也有帮助

最好的选择是使用ReduxForm


推荐阅读