简体   繁体   中英

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ service: string; }

const [serviceList, setServiceList] = useState([{ service: '' }]);

const handleServiceChange = (e:any, index: any) => {
        const { name, value } = e.target;
        const list = { ...serviceList };
        list[index][name] = value;//getting the error here
        setServiceList(list);
    }

This error appears can anyone help me understand the issue and tell me how to solve this in typescript?

You get this error because name can be anything, but elements in your list only have property service . So nothing can guarantee that name value is actually "service" . In general, you should try to avoid using any to type your variables.

Check the following code. I have used ChangeEvent<HTMLInputElement> as an example, but in your case in might be different. In any case, doing this makes typescript know that name is a string.

const handleServiceChange = (e: ChangeEvent<HTMLInputElement>, index: number) => {
  const {name, value} = e.target

  // NOTE the syntax to copy an array!!
  const list = [...serviceList];

  // TS knows that `name` is a string, but it can still be any string.
  // This ensures we only continue if `name === 'service'` and thus makes the error go away
  if (name !== 'service') return;

  list[index][name] = value; // Now we are sure that name == "service"
  setServiceList(list);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM