how do you remove false error in typescript (error: TS2339)?

时间:2018-03-09 19:12:46

标签: angular typescript

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

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.

2 个答案:

答案 0 :(得分:7)

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;

You can also do something like this:

(out as HtmlElement).focus();

Or this:

(<HtmlElement>out).focus();

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

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

答案 1 :(得分:2)

编译器不知道您正在查看的ElementHTMLInputElement,因此它会向您发出警告。如果你肯定你得到HTMLInputElement,那么你可以使用@vincecampanale建议的断言。或者,您可以做一些事情来说服编译器,比如使用user-defined type guard来检查:

function isHTMLInputElement(x: Element): x is HTMLInputElement {
  return (x.tagName.toUpperCase() === 'INPUT');
}

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

// check that out is really an input element
if (!isHTMLInputElement(out)) 
  throw new Error("My life is a lie");

// from here on out, the compiler is convinced that out is an input element
out.focus(); // okay
out.select(); // okay
out.selectionStart = 1; // okay

编译器对上述代码感到满意,因为它使用control flow analysis来识别out.focus()之后和之后的代码只有在out的类型为{{1}时才会运行}。请注意,这不会遇到必须继续重新断言HTMLInputElementout的问题。

希望有所帮助。