Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

querySelector in 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.

question from:https://stackoverflow.com/questions/65643090/passing-dom-object-to-function-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...