0

How can I swap the word email here for value??

  const [state, setState] = useState({
    emailError: '',
  });

const myFunction = (event: ChangeEvent<HTMLInputElement>) => {
   const value = event.target.id; // 'email'
   if (event.target.id === value && state.emailError) validate(value);
//                                         ^
//                                         |___ How can I swap the word email here for value??
}

I tried with this..

if (event.target.id === value && state[value]+Error) validate(value);
Bill
  • 4,614
  • 13
  • 77
  • 132

2 Answers2

3

You can use JS template syntax for this:

if (event.target.id === value && state[`${value}Error`]) validate(value);
Clarity
  • 10,730
  • 2
  • 25
  • 35
  • I get a typescript error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ emailError: string; }'. No index signature with a parameter of type 'string' was found on type '{ emailError: string;}'.ts(7053) – Bill Dec 02 '19 at 17:59
  • You probably need to create an interface for the state and add `[key: string]: string;` there: https://stackoverflow.com/questions/32968332/how-do-i-prevent-the-error-index-signature-of-object-type-implicitly-has-an-an – Clarity Dec 02 '19 at 18:09
0

This is a tricky one since I don't think you can type the ID which would be present on the event. So you may have to explicitly type it for TS to figure it out and also add a type for your state. This may work

const [state, setState] = useState<{ emailError: string }>({
  emailError: '',
});

const myFunction = (event: ChangeEvent<HTMLInputElement>) => {
   const value = event.target.id;
   let stateKey;
   switch(value) {
     case 'email':
       stateKey = 'emailError';
       break;
   }
   if(stateKey) {
     if (event.target.id === value && state[stateKey]) validate(value);
   }
}
pizzarob
  • 11,711
  • 6
  • 48
  • 69