Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i can't setState with dynamic key name in typescript

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.

like image 778
Three Q Avatar asked Jul 12 '19 13:07

Three Q


1 Answers

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

like image 168
VitoMakarevich Avatar answered Oct 05 '22 12:10

VitoMakarevich