Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMLAnchor element download not working in Typescript

I can't get the HTMLAnchor element's download property to work under TypeScript. I'm using the following code:

var element = document.createElement('a');
    element.href = 'data:attachment/csv,' + encodeURIComponent(csvContent);
    element.target = '_blank';
    element.mimeType = "attachment/csv";
    element.download = 'Report.csv';  /* #debug 030314  this line fails */
    document.body.appendChild(element);
    element.click();

It seems that the download property isn't supported in TypeScript. Is there a work-around, that adds the .csv suffix to the file? - Is it possible to bypass TypeScript and call the Javascript code directly?

like image 842
ryokan Avatar asked Nov 30 '22 02:11

ryokan


2 Answers

You can easily add it yourself:

// Tell TypeScript about it
interface HTMLAnchorElement{
    download:string;    
}


var element = document.createElement('a');
    element.href = 'data:attachment/csv,' + encodeURIComponent(csvContent);
    element.target = '_blank';
    element.mimeType = "attachment/csv";
    element.download = 'Report.csv';  /* No error on this line anymore */
    document.body.appendChild(element);
    element.click();
like image 105
basarat Avatar answered Dec 04 '22 07:12

basarat


The download attribute hasn't been widely accepted yet, so they haven't implemented it.

You can always fall back to the completely supported setAttribute:

element.setAttribute("download", "Report.csv");
like image 35
WiredPrairie Avatar answered Dec 04 '22 06:12

WiredPrairie