打字稿中的查询选择器 [英] querySelector in Typescript

查看:17
本文介绍了打字稿中的查询选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让 TypeScript 不抛出错误 'TS2339: property value does not exist on type Element' 对于这样的代码:

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

铸造为 <HTMLInputElement >导致代码完全中断.

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

Typescript 似乎不能很好地处理涉及 DOM 的事情,除非我遗漏了一些东西;即它为可以返回任何元素的函数选择特定而不是一般.

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.

推荐答案

querySelector 方法返回 Element |null.
如果您没有使用 strictNullChecks 然后 元素,并且它没有 value 成员.

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

因此将其转换为 HTMLInputElement 正如我在评论中所写的那样:

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.

querySelector 方法是通用的,所以你也可以这样做:

The querySelector method is generic so you can also do:

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

strictNullChecks 的情况下,如果您确定元素在那里,您可以使用 非空断言运算符:

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

这篇关于打字稿中的查询选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆