angular - 你如何删除 typescript 中的错误错误(错误: TS2339)?

标签 angular typescript

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/

相关文章:

angular - Kendo for Angular - 布局控件不起作用

angular - mat-form-field'不是 Angular 已知元素

javascript - 如何配置 TypeScript 以针对不正确的导入语句抛出错误/警告?

angular - 拦截来自 Angular2 的所有 HTTP 请求

typescript - 为什么我会收到此消息(错误 : TS2376) while running oak.?正文中的错误详细信息

angular - 具有延迟加载的多级模块不起作用

angular - 通过 Angular 9 Reactive Forms 对一个输入使用多种模式的方法

与变量一起使用的 Angular 点击

node.js - 如何运行用 TypeScript 编写的 Mocha 测试?

javascript - 在 Angular 12 中过滤 NavigationEnd 事件?