typescript 打字稿中的查询选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43032004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
querySelector in Typescript
提问by Turtles Are Cute
Is there a way to make TypeScript not throw the error 'TS2339: property value does not exist on type Element' for code like this?:
有没有办法让 TypeScript 不为这样的代码抛出错误“TS2339:类型元素上不存在属性值”?:
myRow.querySelector('.my-class').value = myVal
Casting as < HTMLInputElement > Causes the code to break entirely.
Casting as < HTMLInputElement > 导致代码完全中断。
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.
一般而言,Typescript 似乎不能很好地处理涉及 DOM 的事情,除非我遗漏了一些东西;即它为可以返回任何元素的函数选择特定而不是一般。
回答by Nitzan Tomer
The querySelectormethod returns Element | null
.
If you're not using strictNullChecks
then Element, and it doesn't have the value
member.
该querySelector方法返回Element | null
。
如果您不使用strictNullChecks
then Element,并且它没有value
成员。
And so casting it to HTMLInputElement
as I wrote in my comment works:
因此,HTMLInputElement
正如我在评论中所写的那样将其转换为有效:
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:
该querySelector
方法是通用的,因此您还可以执行以下操作:
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:
而在的情况下,strictNullChecks
如果你确定该元素是否有可以使用非空断言操作:
document.getElementById('my-row')!.querySelector<HTMLInputElement>('.myClass')!.value