3

HTML form implemented with react stateful component. I am trying to write some generic on change handler for form elements but don't succeed to get it typed properly. Here is the code:

interface SignupState {
    username: string
    email: string
    password: string
    password_confirmation: string
}

class Signup extends React.Component<{}, SignupState> {
    ....
    onFieldUpdate: (k: keyof SignupState) => (e: React.ChangeEvent<HTMLInputElement>) => void = (k) => {
        return (e) => {
            this.setState({
                [k]: e.currentTarget.value
            });
        }
    };
}

I thought that this way I will be able to put something like <input onChange={this.onFieldUpdate('username')} /> but have following error on setState call:

Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'SignupState | ((prevState: Readonly<SignupState>, props: Readonly<{}>) => SignupState | Pick<SignupState, "username" | "email" | "password" | "password_confirmation"> | null) | Pick<...> | null'.
  Type '{ [x: string]: string; }' is missing the following properties from type 'Pick<SignupState, "username" | "email" | "password" | "password_confirmation">': username, email, password, password_confirmation  TS2345
Boffin
  • 570
  • 2
  • 7
  • 21

0 Answers0