将JS函数转换为TS

时间:2019-07-25 14:53:28

标签: javascript angular typescript

我正在使用Angular,我需要将以下JS转换为TS函数:

<input type="button" (click)="tableToExcel('testTable')" value="Export to Excel">
var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()

1 个答案:

答案 0 :(得分:0)

我已经将您的函数转换为TypeScript函数,并对其进行了重构。将来,您应该为函数使用更多的描述性名称,因为很难理解所有操作。

const tableToExcel = (() => {
    const uri = 'data:application/vnd.ms-excel;base64,'
    const template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    const base64 = (str: string) =>
        btoa(unescape(encodeURIComponent(str)))
    const format = (str: string, c: any) =>
        str.replace(/{(\w+)}/g, (_: string, p: any) => c[p])
    return (table: Element | string, name?: string) => {
        if (typeof table === 'string')
            table = document.getElementById(table).innerHTML
        location.href = `${uri}${base64(format(template, { worksheet: name || 'Worksheet', table }))}`
    }
})()