首页 > 其他分享> > TypeScript语法错误:Argument of type ‘string‘ is not assignable to parameter of type ‘Element‘. 解决方法
TypeScript语法错误:Argument of type ‘string‘ is not assignable to parameter of type ‘Element‘. 解决方法
作者:互联网
问题描述
DOM插入元素节点报错。
TypeScript语法错误:
TS2345: Argument of type ‘string’ is not assignable to parameter of type ‘Element’.
类型"string"的参数不能赋给类型"Element"的参数。
报错内容以及对应代码:
解决方法
报错的原因在于,该函数可接收的参数类型和实际接收的不匹配。
所以解决的方法是,将第二个参数转换成Element类型;或者更换另一种方法,插入元素的同时,还支持string类型的参数传入。
1. 将第二个参数转换成Element类型
先用createElement
方法创建元素后再插入元素。
let newDiv: HTMLElement = document.createElement("div");
this.element.insertAdjacentElement("beforeend", newDiv);
2. 更换成另外一种插入方法
insertAdjacentHTML
,这个方法的第二个参数为string类型,并且实现的效果相同。
this.element.insertAdjacentHTML("beforeend", "<div></div>");
使用以上一种方法后,ts检查的时候就不会报错。
标签:assignable,string,语法错误,Element,报错,类型,参数,type 来源: https://blog.csdn.net/weixin_45196863/article/details/119111024