Skip to content Skip to sidebar Skip to footer

React Typescript: Argument Of Type '{ [x: Number]: Any; }' Is Not Assignable To Parameter Of Type

I added onChange method in my project(React, TS, Mobx), but I am getting an error: Argument of type '{ [x: number]: any; }' is not assignable to parameter of type I am new to Type

Solution 1:

You need to tell Typescript that your object will have one or more property from IAddPlayerFormState, but not necessarily all properties. You can do it like this:

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

Solution 2:

Using this syntax got rid of the error for me:

const myFunction = (e) => {
    returnthis.setState({...this.state, [e.target.id]: e.target.value});
}

Solution 3:

Your state shape is this:

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

and you are calling setState with this:

{any: any}

You can change only values: playerName and isDisabled not any. If you rewrite function signature as

public onChange(event: { target: { name: "playerName"|"isDisabled"; value: any; }; })

or better

public onChange(event: { target: { name: keyof IAddPlayerFormState ; value: any; }; })

it should be ok for typescript. Btw this code will not work though. Change input name :). I hope this answer is clear, if not i will edit that.

Solution 4:

All u need to do is specify which item you want to update/change

this.setState({value:value});
type ItemState = {
    value?: string;// The state I want to update
};

#In your case would be

this.setState({playerName : new_value});

Post a Comment for "React Typescript: Argument Of Type '{ [x: Number]: Any; }' Is Not Assignable To Parameter Of Type"