[英]Argument of type 'File' is not assignable to parameter of type 'never'. React with TypeScript
How can I set the correct type in useState so I can push image as File in array?如何在 useState 中设置正确的类型,以便可以将图像作为文件推送到数组中?
Here is my useState:这是我的使用状态:
const [colorsAndImages, setColorsAndImages] = useState([{ images: [], colors: '' }])
Here is where I'm trying to push the image but I'm getting an error:这是我试图推送图像但出现错误的地方:
const handleSetImage = (event: React.ChangeEvent<HTMLInputElement>, index: number) => {
const file = event.target.files;
const list = [...colorsAndImages]
list[index].images.push(file?.item(0)!)
setColorsAndImages(list)
};
The error is on...(file?.item(0)!)错误是...(文件?。项目(0)!)
Argument of type 'File' is not assignable to parameter of type 'never'.
“文件”类型的参数不能分配给“从不”类型的参数。
When using the useState
hook without an explicit generic, TypeScript will try to infer the type from the initial passed value.当使用没有显式泛型的
useState
钩子时,TypeScript 将尝试从初始传递的值推断类型。
Since your initial value includes an empty array (for images
), TypeScript is unable to determine the type of the values that will be in that array and so assigns it the type never
.由于您的初始值包含一个空数组(对于
images
),因此 TypeScript 无法确定该数组中的值的类型,因此将其分配为never
类型。
To fix this, explicitly specify the type of your state when you initialize it:要解决此问题,请在初始化时明确指定 state 的类型:
const [colorsAndImages, setColorsAndImages] = useState<{images: File[], colors: string}[]>([{ images: [], colors: '' }])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.