类型'{{[x:string]:string;}' [英] Property is missing in type '{ [x: string]: string; }'

查看:186
本文介绍了类型'{{[x:string]:string;}'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此React应用程序中,有一个带有一些输入字段的表单.这些字段都使用 this.handleChange onChange 属性.

In this react app there is a form with a few input fields. These fields all use this.handleChange with the onChange attribute.

private handleChange = (event: React.FormEvent<HTMLInputElement>) => {
    let target = event.target as HTMLInputElement;
    this.setState({
        [target.name]: target.value
    });
};

我得到的打字稿错误是:

The typescript error I get is:

ERROR in [at-loader] ./src/components/FormSubmitHighScore.tsx:43:23 
TS2345: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'Pick<State, "first_name" | "last_name" | "email_address" | "school_name" | "region" | "submitted">'.
Property 'first_name' is missing in type '{ [x: string]: string; }'.

因此,通过动态设置状态名称字段(基于正在使用的输入),将触发此Typescript错误(但它确实在浏览器中有效).

So by setting the state name field dynamically (based on what input is being used) this Typescript error gets triggered (but it does work in the browser).

在这种情况下如何指定正确的类型?

How would I specify a correct type in this context?

推荐答案

不幸的是,直到这些 错误已修复-您必须采用一些丑陋的解决方法,例如:

Unfortunately until these bugs are fixed - you have to go with some ugly workarounds like:

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

这篇关于类型'{{[x:string]:string;}'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆