Home > Software engineering >  Property 'item' is missing in type 'File[]' but required in type 'FileList&
Property 'item' is missing in type 'File[]' but required in type 'FileList&

Time:08-02

I would like to put files into file type input and then in the class fetch and set. The getter looks like this and it works, but I have a problem with the setter because there is an error: "Property 'item' is missing in type 'File []' but required in type 'FileList'". I created an auxiliary interejs to retrieve specific properties.

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;
    }
}

CodePudding user response:

  1. You cannot name your class File. Since File is an interface defined by TypeScript. (Not sure if you are trying to override the native type, which is something I wouldn't recommend). You should change File to something else, eg. InputFile, which would already be helpful.

  2. In the line:

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

The type of input variable is FileList.

  • FileList is a superset of the type File.

  • Hence, you can assign FileList type to File in your getter.

  • However, in your setter, you cannot assign a File[] to FileList.

Changing the return type of your getter to FileList and making corresponding changes in your setter should fix the problem.

Ultimately, your class could look something like:

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;
    }
}

I hope this helps!

CodePudding user response:

As far as I understood the Documentation, you seem to override the entire FileList thats stored in the HTMLInputElement.files property. The property expects the new Value to be of a similar Type as FileList.
But it seems that your Definition of File[] misses the neccessary Property of item.

But instead to try to recreate the FileList Type, i would recommend to use the same Types and Features as are native implemented.

I've linked you a reference, where a similar Issues were tackled and there your should find a suitable solution: Similar Issue

  • Related