score:2

Accepted answer

you need to assert that e.target.name, which is always just string, is in fact a valid key of inputs.field.

const eventname = e.target.name as keyof paymentform['field'];

however your update syntax is not right. you are setting top-level properties of inputs and you are using the value of inputs.field[eventname] as the property name.

you could do a nested update:

setinputs(inputs => ({ 
  ...inputs, 
  field: { 
    ...inputs.field, 
    [eventname]: eventvalue 
  }
}));

but why do we need to have this field property at all? it's the only property in inputs so why don't we just make it be the entire state.

interface fields {
  paymentmethod: string;
  amount: string;
  receiptcode: string;
  paymentdate: string;
  paymentsourceid: string;
}

const paymentform = () => {
  const [fields, setfields] = usestate<fields>({
    paymentmethod: "",
    amount: "",
    receiptcode: "",
    paymentdate: "",
    paymentsourceid: "paymentsourceid"
  });

  const changedhandler = (
    e: react.changeevent<htmlinputelement | htmlselectelement>
  ) => {
    setfields((fields) => ({
      ...fields,
      [e.target.name as keyof fields]: e.target.value
    }));
  };

  return <></>;
};

score:1

your eventname can be a union of the field keys. try this.

type eventname = 'paymentmethod' | 'amount' | 'recieptcode' ...etc;
const eventname = e.target.name as eventname; // or

const eventname = e.target.name as keyof paymentform['field'];


Related Query

More Query from same tag