TypeScript语法错误:Argument of type ‘string‘ is not assignable to parameter of type ‘Element‘. 解决方法

Posted 程序员超时空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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检查的时候就不会报错。

以上是关于TypeScript语法错误:Argument of type ‘string‘ is not assignable to parameter of type ‘Element‘. 解决方法的主要内容,如果未能解决你的问题,请参考以下文章