Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector in Typescript

Tags:

typescript

Is there a way to make TypeScript not throw the error 'TS2339: property value does not exist on type Element' for code like this:

myRow.querySelector('.my-class').value = myVal 

Casting as < HTMLInputElement > Causes the code to break entirely.

Typescript seems to not handle things involving the DOM well in general, unless I'm missing something; ie it chooses specific over general for functions that could return any element.

like image 284
Turtles Are Cute Avatar asked Mar 26 '17 17:03

Turtles Are Cute


People also ask

What is the type of querySelector in TypeScript?

The querySelector method has a return type of Element | null . If no element with the provided selector exists in the DOM, the method returns a null value.

What is querySelector in angular?

querySelector() The querySelector() method of the Element interface returns the first element that is a descendant of the element on which it is invoked that matches the specified group of selectors.

What does querySelector () do?

Document.querySelector() The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.


2 Answers

The querySelector method returns Element | null.
If you're not using strictNullChecks then Element, and it doesn't have the value member.

And so casting it to HTMLInputElement as I wrote in my comment works:

let myRow = document.getElementById('my-row'); (myRow.querySelector('.myClass') as HTMLInputElement).value = " a vaule"; 

The error you are receiving is a result of forgetting the semicolon at the end of the first line, what happens is that the compiler thinks that you're trying to do this:

document.getElementById('my-row')(myRow.querySelector('.myClass') as HTMLInputElement) 

Don't forget to end lines with semicolons.


Edit

The querySelector method is generic so you can also do:

document.getElementById('my-row').querySelector<HTMLInputElement>('.myClass').value 

And in case of strictNullChecks if you're sure the element is there you can use the Non-null assertion operator:

document.getElementById('my-row')!.querySelector<HTMLInputElement>('.myClass')!.value 
like image 192
Nitzan Tomer Avatar answered Sep 27 '22 20:09

Nitzan Tomer


//  define export const $ = <T>(selector, scope = document): T =>   scope.querySelector(selector);   //  use const $account: HTMLInputElement = $("#login-account");  // example tips for  .value const account = $account.value 
like image 24
ifredom Avatar answered Sep 27 '22 20:09

ifredom