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

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


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


The compiler doesn't know that the Element you are looking at is an HTMLInputElement, so it warns you. If you are positive you are getting an HTMLInputElement, then you can use an assertion like @vincecampanale suggests. Or, you can do something to convince the compiler, like using a user-defined type guard to check:

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 elementif (!isHTMLInputElement(out))   throw new Error("My life is a lie");// from here on out, the compiler is convinced that out is an input elementout.focus(); // okayout.select(); // okayout.selectionStart = 1; // okay

The compiler is happy with the above code, because it uses control flow analysis to recognize that the code at and after out.focus() will only run if the type of out is HTMLInputElement. Note that this does not suffer from the issue where you have to keep re-asserting that out is an HTMLInputElement.

Hope that helps.