2

I am writing a web application using Angular 4 and Typescript. I need the date of a file to upload and try to use the File objects lastModified property, but Typescript gives me an error

Property 'lastModified' does not exist on type 'File'.

If I look in the definition it instead have the lastModifiedDate as a property. According to https://developer.mozilla.org/en-US/docs/Web/API/File/lastModifiedDate that property is depriciated. I have however tried it and it works in Chrome, but fails in Safari.

How can I use File lastModified property from Typescript?

Jørgen Rasmussen
  • 1,143
  • 14
  • 31

2 Answers2

5

Try

interface MyFile extends File {
    lastModified: any;
}

let myFile = <MyFile>originalFile;
let lm = myFile.lastModified;
Andrey
  • 559
  • 3
  • 6
0

Also for lastModifiedDate, which is deprecated but for now still around in Chrome and was the only option in IE:

// use non-deprecated lastModified field instead 
new Date(file.lastModified)


// in-line type assertion
(file as unknown as { lastModifiedDate: Date }).lastModifiedDate

// type assertion with special type
type DateFile = File & {
  lastModifiedDate: Date;
};
...
(file as DateFile).lastModifiedDate

will prevent TS2551 Property 'lastModifiedDate' does not exist on type 'File'. Did you mean 'lastModified'? ts(2551) error by using lastModified instead or asserting that it exists.

cachius
  • 1,743
  • 1
  • 8
  • 21