简体   繁体   English

将 javascript 转换为 TypeScript 的问题

[英]Issue in converting javascript to TypeScript

Syntax issue in typescript.. I wrote code in javascript and try to put it in ts file.打字稿中的语法问题.. 我用 javascript 编写代码并尝试将其放入 ts 文件中。 Made some changes, but still showing issues with cells.进行了一些更改,但仍显示单元格问题。

class X {
  public appendTableColumn() {
    var tbl = <HTMLTableElement>document.getElementById("myTable"); // table reference
    //var colnum= parseInt(tbl.rows[0].cells.length) - 1;
    // i;
    var m = parseInt(tbl.rows[0].cells.length) + 1;
    // open loop for each row and append cell
    for (var i = 0; i < tbl.rows.length; i++) {
      var k = parseInt(i) + 1;

      //createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), "R"+ tbl.rows.length +"C"+ k, 'col');
      this.createCell(
        tbl.rows[i].insertCell(tbl.rows[i].cells.length),
        "",
        "col",
      );
      var x = document.getElementById("myTable").rows[i].cells;
      var btnName = "R" + k + "C" + m;
      x[tbl.rows[i].cells.length - 1].id = "td" + btnName;
      x[tbl.rows[i].cells.length - 1].innerHTML =
        '<button class="button" onclick="reply_click(this.id);" id=' +
        btnName +
        ">Manage Items</button>";
      //alert(btnName);
    }
  }
}

document.getElementById is only guaranteed to return an HTMLElement , but you're implicitly expecting it to be a table, which TypeScript can't guarantee because it doesn't look at your HTML code (among other reasons). document.getElementById只保证返回一个HTMLElement ,但你隐含地期望它是一个表,TypeScript 不能保证,因为它不查看你的 HTML 代码(以及其他原因)。

When you have an element type assumption like this, what you need to do is use a type assertion.当您有这样的元素类型假设时,您需要做的是使用类型断言。

var x = (<HTMLTableElement>document.getElementById("myTable")).rows[i].cells;

As an aside, you don't need to pass variables of type number to parseInt . parseInt ,您不需要将number类型的变量传递给parseInt The following lines:以下几行:

var m = parseInt(tbl.rows[0].cells.length) + 1;
// ...
var k = parseInt(i) + 1;

Should instead be written as:应该写成:

var m = tbl.rows[0].cells.length + 1;
// ...
var k = i + 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM