start file download in typescript

To start a file download in TypeScript, you can use the anchor element's download attribute with the click() method. Here's an example:

index.ts

function downloadFile(url: string, fileName: string) {
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  link.click();
}

// Example usage
downloadFile('http://example.com/file.pdf', 'myFile.pdf');
242 chars
11 lines

In the above code, a function downloadFile is created that takes url and fileName as arguments. Inside this function, a new a (anchor) element is created, with the href set to the URL of the file to be downloaded and the download attribute set to the desired file name. Finally, the click() method is called on the anchor element to trigger the download in the browser.

This code will work in all modern browsers (including Chrome, Firefox, and Edge). However, in some older browsers, the download attribute is not supported and the link will be opened instead of downloading the file.

gistlibby LogSnag