[英]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
.您会收到此错误,因为
name
可以是任何东西,但列表中的元素只有属性service
。 So nothing can guarantee that name
value is actually "service"
.所以没有什么可以保证
name
值实际上是"service"
。 In general, you should try to avoid using any
to type your variables.通常,您应该尽量避免使用
any
来键入变量。
Check the following code.检查以下代码。 I have used
ChangeEvent<HTMLInputElement>
as an example, but in your case in might be different.我以
ChangeEvent<HTMLInputElement>
为例,但在您的情况下可能会有所不同。 In any case, doing this makes typescript know that name
is a string.无论如何,这样做会让 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.