且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

打字稿中的“EventTarget"类型错误不存在属性“文件"

更新时间:2022-05-18 08:57:38

e.target 属性类型取决于您在 getElementById(...)上返回的元素>.filesinput 元素的一个属性:https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

The e.target property type depends on the element you are returning on getElementById(...). files is a property of input element: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

在这种情况下,TypeScript 编译器不知道您正在返回 input 元素,而且我们没有专门用于此的 Event 类.所以,你可以像下面的代码一样创建一个:

In this case, the TypeScript compiler doesn't know you are returning an input element and we dont have an Event class specific for this. So, you can create one like the following code:

interface HTMLInputEvent extends Event {
    target: HTMLInputElement & EventTarget;
}

document.getElementById("customimage").onchange = function(e?: HTMLInputEvent) {
    let files: any = e.target.files[0]; 
    //...
}