Typescript

Asked

Viewed 121 times

1

So guys, I’m making an html page in which I’m using Typescript, and I wasn’t able to get the value of an id, until I saw in a query in the stack that should be used this way

(<HTMLInputElement>document.getElementById('ID')).value

to get value. I know that Javascript is simpler... it doesn’t need the <HTMLInputElement>.

Can you explain to me why I need to use this and how it would be an easier way for me, that I’m making a code with many variables, to be able to use the variables without having to type in the form of the first example.

OBS: It wouldn’t be practical for me to put it this way:

var exemplo = (<HTMLInputElement>document.getElementById('EXEMPLO')).value;

because there are places I need to use the same ID to do something other than take value... like:

(<HTMLInputElement>document.getElementById('EXEMPLO')).checked = true;

2 answers

2


'Cause you need to wear this?

It is because the method getElementById returns a HTMLElement or null. HTMLElement is a class that does not own the property value, so if you want to access such a property, you need to cast in the element to treat it as a HTMLInputElement, class to which it extends HTMLElement and owns the property value.

Casting is not a safe operation, there is no way to guarantee at compile time that the element found is in fact a HTMLInputElement, and therefore ideally you should use smart cast, as in the example:

const elem = document.getElementById('ID');
const elemValue = elem instanceof HTMLInputElement ? elem.value : '';

How the condition ensures that the element found is in fact a HTMLInputElement, you can access the properties of a HTMLInputElement without the compiler being error-free, and there is no risk of error at runtime. This also works with ifs

if (elem instanceof HTMLInputElement) {
    // ...
}

How can you make it less verbose?

Disabling the on option tsconfig.json. Despite the verbosity, I don’t recommend doing this, as I would be defeating the safe typing purpose of Typescript. This is one of the compromises you need to make to use language.

0

Are you using multiple places an ID? Id is unique, if you want to use in multiple places must use class

document.getElementsByClassName('EXEMPLO').value 
  • I’m not using it in several places in html.... but I have to call it in different places in Typescript... so I keep repeating the code (<HTMLInputElement>document.getElementById('ID')).value, turns out the code gets confused

  • Is it to get the most current value? if it’s not just using a variable, is it open source? could post an example, if the project is large it would be better to use some framework as angular or a lib like jquery / React .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.