javascript - react typescript : Argument of type '{ [x: number]: any; }' is not assignable to parameter of type

标签 javascript reactjs typescript mobx

我在我的项目(React、TS、Mobx)中添加了 onChange 方法,但收到错误: Argument of type '{ [x: number]: any; }' 不可分配给类型的参数

我是 TypeScript 新手,不确定为什么会发生这种情况。可能是什么问题?

(parameter) event: {
    target: {
        name: any;
        value: any;
    };
}

Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'IAddPlayerFormState | ((prevState: Readonly, props: Readonly) => IAddPlayerFormState | Pick | null) | Pick<...> | null'.

enter image description here

import React, { Component } from 'react';
import ViewStore from '../../../store/ViewStore';
import { TextField } from './../../../utils';

interface IAddPlayerFormProps {
  viewStore?: ViewStore; // Optional ViewStore
}

interface IAddPlayerFormState {
  playerName: string;
  isDisabled: boolean;
}

class AddPlayerForm extends Component<IAddPlayerFormProps, IAddPlayerFormState> {
  constructor(props: Readonly<IAddPlayerFormProps>) {
    super(props);

    this.state = {
      isDisabled: false,
      playerName: '',
    };
  }

  public onChange(event: { target: { name: any; value: any; }; }) {
    this.setState({ [event.target.name]: event.target.value });
    console.log('On Change!');
  }

  public handleSubmit = () => {
    console.log('On submit!');
  }

  public render() {
    const { isDisabled } = this.state;

    return (
      <form onSubmit={this.handleSubmit}>
        <TextField
          type="text"
          name="name"
          value={name}
          placeholder="Add player"
          onChange={this.onChange}
          disabled={isDisabled}
        />

        <input type="submit" />
      </form>
    );
  }
}

export default AddPlayerForm;

最佳答案

您需要告诉 Typescript 您的对象将具有 IAddPlayerFormState 中的一个或多个属性,但不一定是所有属性。你可以这样做:

public onChange(event: { target: { name: any; value: any; }; }) {
  const newState = { [name]: value } as Pick<IAddPlayerFormState, keyof IAddPlayerFormState>;
  this.setState(newState);
  console.log("On Change!");
}

关于javascript - react typescript : Argument of type '{ [x: number]: any; }' is not assignable to parameter of type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55729742/

相关文章:

events - signalR调用客户端时如何在Angular2中抛出事件

数组的 Angular 2 插值不起作用

javascript - 查看Node.js String.prototype的方法?

javascript - Tinymce 格式的内容未从数据库中显示

javascript - Electron 上的多个http页面

javascript - 为什么当我导航到另一个页面时 reCaptcha 消失了?

javascript - 不返回带有通过 JavaScript 中的 ajax 填充的选项的选择对象

javascript - 如何为空数组定义 TypeScript 接口(interface)?

javascript - Flex 子元素在非常小的宽度上消失

typescript -在函数返回之前等待 promise 解决