代码之家  ›  专栏  ›  技术社区  ›  alphapilgrim

如何扩展dom文件列表类型以便我可以数组过滤器?

  •  1
  • alphapilgrim  · 技术社区  · 6 年前

    我试过几种不同的方法 FileList 筛选而不获取任何类型脚本类型错误。我让它和一个简单的 for-loop . 但在arrow函数的作用下,它是一个一行程序,而对于带有for循环的两行程序。有人有什么建议吗?事先谢谢。请看下面我到目前为止所做的尝试。

    onDrop(evt: DragEvent) {
      let files: FileList = evt.dataTransfer.files;
    
      // results in: Property 'item' is missing in type 'File[]' but required in type 'FileList'.ts(2741)
    
      files = Array.from(files).filter((file: File) => file.type === 'text/csv');
    
    
      // Type 'FileList' is not an array type.ts(2461)
      [...files].filter((file: File) => file.type === 'text/csv');
    }
    
    // no type errors
    const filteredFileList = [];
    for (let index = 0; index < files.length; index++) {
      const file: File = files[index];
      if (file.type === 'text/csv') {
        filteredFileList.push(file);
      }
    }
    

    TSOCONT.JSON

    {
      "compileOnSave": false,
      "compilerOptions": {
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "outDir": "./dist/out-tsc",
        "baseUrl": "src",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2017", "dom"]
      },
      "angularCompilerOptions": {
        "enableIvy": false
      }
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Get Off My Lawn    6 年前

    你的问题是你试图设置 File[] FileList ,您不能这样做,因为它们是两种不同的类型,并且不能互相继承。

    你需要保存 文件[] 到一个新的变量,就像在for循环中一样。

    onDrop(evt: DragEvent) {
      let files: FileList = evt.dataTransfer.files;
    
      const filteredFileList: File[] = [...files].filter((file: File) => file.type === 'text/csv');
    }
    

    您需要添加 "dom.iterable" 对你 libs 列出并使用目标 es2015 或稍后,以支持转换 文件作者 文件[] 使用 [...files] .

    推荐文章