简体   繁体   English

类型 '{ [x: string]: string; 中缺少属性 }'

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

In this react app there is a form with a few input fields.在这个反应应用程序中,有一个带有几个输入字段的表单。 These fields all use this.handleChange with the onChange attribute.这些字段都使用this.handleChangeonChange属性。

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; }'.

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).因此,通过动态设置状态名称字段(基于正在使用的输入)这个 Typescript 错误被触发(但它确实在浏览器中工作)。

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);

To avoid "any" linter warning I use:为了避免“任何” linter 警告,我使用:

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

Passing a function to setState works too.将函数传递给 setState 也可以。 My guess is that it is because you are spreading state, so typescript knows it has all the properties of state.我的猜测是因为你在传播状态,所以打字稿知道它具有状态的所有属性。

    this.setState(state => ({
      ...state,
      [name]: value,
    }));

I was getting a similar error to what you were getting.我遇到了与您遇到的类似的错误。 Here is my implementation for a change handler:这是我对更改处理程序的实现:

  onChange = (name: keyof ComponentState, value: any) => {
    this.setState(state => ({
      ...state,
      [name]: value,
    }));
  };

I had the same issue when i was managing my props using react with typescript as a programming language.当我使用typescript react编程语言来管理我的道具时,我遇到了同样的问题。 I was using CBC so i manage to get a work around on this by setting the state values to be optional.我使用的是CBC ,所以我设法通过将状态值设置为可选来解决这个问题。 Here is my class based component where i'm getting track of the state of username , email and password :这是我基于类的组件,我在其中跟踪usernameemailpassword的状态:

interface Props {}
interface State {
  username?: string;
  email?: string;
  password?: string;
}
export default class App extends React.Component<Props, State> {
  constructor(props: any) {
    super(props);
    this.state = {
      username: "",
      password: "",
      email: "",
    };
  }

  onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
  };
  onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    this.setState((state) => ({
      ...state,
      [name]: value,
    }));
  };

  render(): React.ReactNode {
    const { username, password, email } = this.state;
    return (
      <div className="app">
        <form onSubmit={this.onSubmit}>
          <input
            type="text"
            placeholder="username"
            name="username"
            value={username}
            onChange={this.onChange}
          />
          <input
            type="text"
            placeholder="email"
            name="email"
            value={email}
            onChange={this.onChange}
          />
          <input
            type="text"
            placeholder="password"
            name="password"
            value={password}
            onChange={this.onChange}
          />
          <button type="submit">register</button>
        </form>
      </div>
    );
  }
}

By setting fields optional in the State type you don't need to do this:通过在State类型中设置可选字段,您不需要这样做:

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

Because typescript knows how to handle this.因为typescript知道如何处理这个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型“ any []”中缺少属性“ 0”,但是类型“ [{{id:string; gp:布尔值; }] - Property '0' is missing in type 'any[]' but required in type '[{ id: string; gp: boolean; }] TS2741 类型 &#39;{ 标签:字符串; 中缺少属性 &#39;0&#39; Javascript - TS2741 Property '0' is missing in type '{ label: string; } Javascript 字符串流类型中缺少属性映射 - Property map is missing in String Flowtype “DefaultRootState”类型中缺少属性“X”-但该属性是在接口中声明的 - Property 'X' is missing in type 'DefaultRootState' - but the property is declared in Interface 类型“字符串”上不存在属性“substr”| 细绳[]' - Property 'substr' does not exist on type 'string | string[]' 字符串变量值作为类型中的属性 - String variable value as a property in a type Facebook的自定义故事,#100对象缺少必需的值……未提供类型为&#39;string&#39;的属性&#39;appnamespace:prop&#39;。” - Facebook custom story, #100 Object Missing a Required Value… property 'appnamespace:prop' of type 'string' was not provided." 自定义字符串 - 缺少:属性列表后 - Custom String - Missing : after property list 类型“{}”中缺少属性“x”,但类型“Pick”中需要<Interface, "x"> &#39;。 TS2741 - Property 'x' is missing in type '{}' but required in type 'Pick<Interface, "x">'. TS2741 类型“ {} |属性不存在日期” {date:string; }&#39; - Property 'date' does not exist on type '{} | { date: string; }'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM