繁体   English   中英

“文件[]”类型中缺少属性“项目”,但在“文件列表”类型中是必需的

[英]Property 'item' is missing in type 'File[]' but required in type 'FileList'

我想将文件放入文件类型输入中,然后在 class 中获取和设置。 getter 看起来像这样并且它可以工作,但是我的 setter 有问题,因为有一个错误:“'File []' 类型中缺少属性'item',但在'FileList' 类型中是必需的”。 我创建了一个辅助 interejs 来检索特定属性。

interface IFile{
url: string;
name: string;
}
class File{
    [x: string]: any;
   
    get files(): File[] {
        const input = (this.querySelector('[name="Input"]') as HTMLInputElement).files;
        return input as any;
    }

    
    set files(value: File[]) {
        (this.querySelector('[name="Input"]') as HTMLInputElement).files = value;
    }
}

据我了解文档,您似乎覆盖了存储在 HTMLInputElement.files 属性中的整个 FileList 。 该属性期望新值的类型与 FileList 相似。
但似乎您对 File[] 的定义错过了item的必要属性。

但是为了尝试重新创建 FileList 类型,我建议使用与本机实现相同的类型和功能。

我已经为您链接了一个参考,其中解决了类似的问题,您应该在那里找到合适的解决方案: 类似问题

  1. 您不能命名您的 class File 由于File是 TypeScript 定义的接口。 (不确定您是否要覆盖本机类型,这是我不推荐的)。 您应该将File更改为其他内容,例如。 InputFile ,这已经很有帮助了。

  2. 在行中:

const input = (this.querySelector('[name="Input"]') as HTMLInputElement).files;

input变量的类型是FileList

  • FileListFile类型的超集。

  • 因此,您可以在 getter 中将FileList类型分配给File

  • 但是,在您的设置器中,您不能将File[]分配给FileList

将 getter 的返回类型更改为FileList并在 setter 中进行相应的更改应该可以解决问题。

最终,您的 class 可能看起来像:

class MyFile {
    [x: string]: any;
   
    get files(): FileList {
        const input = (this.querySelector('[name="Input"]') as HTMLInputElement).files;

        if(input === null) {
          // handle null
          throw Error();
        }

        return input;
    }

    
    set files(value: FileList) {
        (this.querySelector('[name="Input"]') as HTMLInputElement).files = value;
    }
}

我希望这有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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