I defined state interface of React component as following.
interface IState {
email: string,
password: string,
errors: object
}
and in text input change event I am trying to set state with dynamic key as below.
handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
this.setState({
[e.target.name]: e.target.value
});
}
However VSCode shows me this error
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)
Any advice would be welcome.
The problem is that e.target.name
should be key of IState
and e.target.value
should be relative type from key in IState
, to fix it you can manually cast type like
this.setState({
[e.target.name]: e.target.value
} as Pick<IState, keyof IState>);
but it disables typescript for this function also you can cast it to any type, but it's unsafe.
Looks like this answer also can be helpful for you
The best option is to use ReduxForm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With