I have this code
interface FormState {
cardNumber: string,
month: string,
year: string
}
handleInputChange = (event: React.ChangeEvent<MaskedInput>) => {
this.setState({
[event.target.name]: event.target.value
});
};
TypeScript doesn't know what the name
property of event.target
is, but I know that it will always match the FormState
keys. Similarly with the value
property.
I tried to fix it with type assertion but still get the error
type ObjectKey<T> = keyof T;
type ValueOf<T> = T[keyof T];
[event.target.name as ObjectKey<FormState>]: event.target.value as ValueOf<FormState>
How can I fix this?
Just add the type for target name in React.ChangeEvent:
handleInputChange = (event: React.ChangeEvent<{name: keyof FormState}>) => {
Since you are handling input change, the better type will be React.ChangeEvent<HTMLInputElement>
:
type TargetName=keyof FormState
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
let name = event.target.name as TargetName
name===''
};