I'm coding Simple LoginForm with react and typescript.
interface State {
username: string;
password: string;
}
class LoginForm extends React.Component<Props, State> {
readonly state: Readonly<State> = {
username: '',
password: ''
}
onChange = (key: keyof State) => (e: React.FormEvent<HTMLInputElement>) => {
const value = e.currentTarget.value;
this.setState({ [key]: value }); // error
}
render() {
return (
...
<TextField
...
onChange={this.onChange('username')}
/>
<TextField
...
onChange={this.onChange('password')}
/>
...
)
}
}
Typescript failed to compile in setState line with is error.
Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'State | ((prevState: Readonly, props: Props) => State | Pick'. Property 'username' is missing in type '{ [x: string]: string; }'.
The 'key' parameter in this.onChange function only allows either 'username' or 'password' as I expected. This means that typescript knows typeof 'key' parameter must be either 'username' or 'password'. This is obvious because I defined it as (key: key of State).
But why in setState function, typeof 'key' parameter changes to just normal string?
Thanks.