[英]Element implicitly has an 'any' type because expression of type 'string | number' can't be used to index type
[英]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);
}
出现此错误,谁能帮我理解这个问题并告诉我如何在打字稿中解决这个问题?
您会收到此错误,因为name
可以是任何东西,但列表中的元素只有属性service
。 所以没有什么可以保证name
值实际上是"service"
。 通常,您应该尽量避免使用any
来键入变量。
检查以下代码。 我以ChangeEvent<HTMLInputElement>
为例,但在您的情况下可能会有所不同。 无论如何,这样做会让 typescript 知道name
是一个字符串。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.