Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a File object in Typescript?

I see that my IDE recognizes File as a Typescript object. Doing a refined search in Google brings me to this page, which has nothing about File objects. File is neither in basic types or in advanced types.

Are File objects in Typescript handled exactly the same way as in Javascript? Are there any breaking differences?

Again, how to instantiate a File type in Typescript?

like image 693
NonCreature0714 Avatar asked Mar 04 '19 22:03

NonCreature0714


1 Answers

The File class is not defined as part of the TypeScript language proper, but rather is a part of the DOM specification. TypeScript provides a standard declaration file for DOM objects as part of the stdlib, which you can view for yourself here:

/** The File interface provides information about files and allows JavaScript in a web page to access their content. */
interface File extends Blob {
    readonly lastModified: number;
    readonly name: string;
}

declare var File: {
    prototype: File;
    new(fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
};

Of course the declaration file itself isn't very user friendly. You'll probably find the MDN DOM API documentation more useful (though note, it's for JavaScript, not TypeScript, so don't expect any explicit type annotations). It provides this example:

var file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});

And although this is technically JavaScript, it will compile just fine as TypeScript, and the inferred type of file will be File.

like image 161
p.s.w.g Avatar answered Sep 20 '22 17:09

p.s.w.g