score:6

Accepted answer

We can use Pick to ensure that you're setting a key that has been defined in your IState interface.

Pick - set state

private handleChange = (e: React.FormEvent<HTMLInputElement>) => {
    const { name, value } = e.currentTarget;
    this.setState({
        [name]: value
    } as Pick<IState, keyof IState>);
};

Or alternative you can use Partial which will make all your state keys optional.

class App extends React.Component<{}, Partial<IState>> {
    // ... rest of component
}

score:2

1.Declare your interface

interface IState {
  login: string;
  password: string;
}

2.Declare your state

const [myState, setMyState] = useState<IState>()

3.Declare your onchange function

const onChange=(e: any): void => {
    const { name, value } = e.currentTarget;
    setMyState({ ...myState, [name]: value });
}

4.Declare your markup

<input name="login" type="text" onChange={onChange}/>

We are using the spread function to maintain and update the state Note that you need to name the markup element with the "name" attribute and it should correspond with your interface attribute

Spread syntax

React naming elements


Related Query

More Query from same tag