Search code examples
javascripthtmlinnerhtml

Type 'HTMLButtonElement' is not assignable to type 'string'.ts(2322)


You have a function that generates "tr" and "td" in the table. With For Loop I put "td" elements into "tr". Actually Everything works. But I am getting an error in Visual Studio Code.

Her is my code:

function setUI(tbody, courseData){

let arrCourse = Object.values(courseData) // parse object to array 
let tr = document.createElement('tr'); // create tr 
let button = document.createElement('button'); // create delete button
button.className = 'btn btn-danger'; // add class to button element
tbody.appendChild(tr); // add tr to tbody
for(let i = 0; i<arrCourse.length+1; i++){
    let td = document.createElement('td'); // create td .
    tr.appendChild(td); // append td to tr
    td.innerHTML = arrCourse[i]; // get index of array then push it to td
    if(i==arrCourse.length+1){
        td.appendChild(button);
    }  
}

}

My error is here: Type 'unknown' is not assignable to type 'string'.ts(2322)

Erros is this line:

td.innerHTML = arrCourse[i]; // get index of array then push it to td

Solution

  • Typescript compiler is not able to infer the type, so it assumes the type to be any. You can solve this problem by setting the type explicitly

    let arrCourse: string[] = Object.values(courseData) // parse object to array