你如何删除打字稿中的错误错误(错误:TS2339)? [英] how do you remove false error in typescript (error: TS2339)?

查看:41
本文介绍了你如何删除打字稿中的错误错误(错误:TS2339)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var out = document.getElementsByClassName('myclass')[0];
out.focus();
out.select();
out.selectionStart =1;

我试图在我的打字稿文件中执行此操作,但由于某种原因它给了我这些错误

I'm trying to do this in my typescript file, but for some reason it gives me these errors

src/app/main/utilities/keyboard/keyboard.component.ts(29,9) 中的错误:错误 TS2339:元素"类型上不存在属性焦点".src/app/main/utilities/keyboard/keyboard.component.ts(30,9): 错误TS2339:元素"类型上不存在属性选择".src/app/main/utilities/keyboard/keyboard.component.ts(31,9): 错误TS2339:元素"类型上不存在属性selectionStart".

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'.

这是说该属性不存在,但确实存在.当我运行它时,一切正常,但我必须在控制台中处理一大块红色文本,这很烦人.

It is saying that the property does not exist, but it does. When I run this, everything works as it should but I have to do with a huge block of red text in my console which is annoying.

推荐答案

您需要将 out 变量类型转换为 HtmlElement 以便 Typescript 知道哪些方法和属性可用.

You need to type cast your out variable to an HtmlElement in order for Typescript to know what methods and properties are available.

var out = document.getElementsByClassName('myclass')[0] as HtmlElement;

你也可以这样做:

(out as HtmlElement).focus();

或者这个:

(<HtmlElement>out).focus();

但是每次使用 out 时都必须重新声明类型.

But then you'll have to re-assert the type every time you use out.

在此处阅读有关类型转换/类型断言的更多信息:https://www.typescriptlang.org/docs/handbook/basic-types.html

Read more about type casting / type assertions here: https://www.typescriptlang.org/docs/handbook/basic-types.html

这篇关于你如何删除打字稿中的错误错误(错误:TS2339)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆