var out = document.getElementsByClassName('myclass')[0];
out.focus();
out.select();
out.selectionStart =1;
我正尝试在我的 typescript 文件中执行此操作,但出于某种原因它给了我这些错误
ERROR in src/app/main/utilities/keyboard/keyboard.component.ts(29,9): error TS2339: Property 'focus' does not exist on type 'Element'. src/app/main/utilities/keyboard/keyboard.component.ts(30,9): error TS2339: Property 'select' does not exist on type 'Element'. src/app/main/utilities/keyboard/keyboard.component.ts(31,9): error TS2339: Property 'selectionStart' does not exist on type 'Element'.
说的是属性不存在,其实是存在的。当我运行它时,一切正常,但我不得不在我的控制台中处理一大块红色文本,这很烦人。
最佳答案
您需要将 out
变量类型转换为 HtmlElement
,以便 Typescript 知道哪些方法和属性可用。
var out = document.getElementsByClassName('myclass')[0] as HtmlElement;
你也可以这样做:
(out as HtmlElement).focus();
或者这个:
(<HtmlElement>out).focus();
但是每次使用 out
时都必须重新声明类型。
在此处阅读有关类型转换/类型断言的更多信息:https://www.typescriptlang.org/docs/handbook/basic-types.html
关于angular - 你如何删除 typescript 中的错误错误(错误: TS2339)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49200604/