React报错之Property 'value' does not exist on type 'HTMLElement'
正文从这开始~
总览
当我们试图访问一个类型为HTMLElement的元素上的value属性时,会产生"Property 'value' does not exist on type 'HTMLElement'"错误。为了解决该错误,在访问属性之前,使用类型断言将元素类型断言为HTMLInputElement。
这里有个示例用来展示错误是如何发生的。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
const input = document.getElementById('message');
// ️ Property 'value' does not exist on type 'HTMLElement'.ts(2339)
console.log(input?.value);
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
我们得到错误的原因是因为,document.getElementById方法返回的类型为HTMLElement | null ,并且value属性不存在于HTMLElement类型上。
类型断言
为了解决该错误,使用类型断言将元素类型断言为HTMLInputElement(或者HTMLTextAreaElement,如果你使用textarea元素键入)。
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
// type element as HTMLInputElement
const input = document.getElementById('message') as HTMLInputElement;
console.log(input?.value); // ️ "Initial value"
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
你也可以在内联中使用一个类型断言,就在访问值属性之前。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
// ️ inline type assertion
const value = (document.getElementById('message') as HTMLInputElement).value;
console.log(value);
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
当我们拥有一个值的类型信息,但是TypeScript无从得知时,就会使用类型断言。
我们有效地告诉TypeScript,
input变量存储了一个HTMLInputElement,不用担心它。
如果你正在使用一个textarea元素,你将使用HTMLTextAreaElement类型来代替。
联合类型
如果你想更精确地控制类型,你可以使用一个联合类型来设置类型为HTMLInputElement | null。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
// type element as HTMLInputElement | null
const input = document.getElementById('message') as HTMLInputElement | null;
console.log(input?.value); // ️ "Initial value"
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
HTMLInputElement | null类型是正确的,因为如果提供id的元素不存在于DOM中,document.getElementById()方法就会返回一个null值。
需要注意的是,我们使用了可选链(?.)操作符来短路运算,如果引用是空值的话(null或者undefined)。
换句话说,如果input变量存储了一个null值,我们就不会试图访问null的属性,而得到一个运行时错误。
类型守卫
你也可以使用一个简单的if语句作为类型守卫,以确保input变量不存储一个null值。
// App.tsx
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
const input = document.getElementById('message') as HTMLInputElement | null;
if (input != null) {
console.log(input.value); // ️ "Initial value"
}
}, []);
return (
<div>
<input id="message" defaultValue="Initial value" />
</div>
);
}
TypeScript知道
input变量在if块中的类型是HTMLInputElement,并允许我们直接访问其value属性。
在类型断言中包含null总是一种最佳实践,因为如果没有找到所提供的id的元素,getElementById方法将返回null。
React报错之Property 'value' does not exist on type 'HTMLElement'的更多相关文章
- React报错之Property 'X' does not exist on type 'HTMLElement'
正文从这开始~ 总览 在React中,当我们试图访问类型为HTMLElement 的元素上不存在的属性时,就会发生Property 'X' does not exist on type 'HTMLEl ...
- React报错之Property 'value' does not exist on type EventTarget
正文从这开始~ 总览 当event参数的类型不正确时,会产生"Property 'value' does not exist on type EventTarget"错误.为了解决 ...
- React报错之Parameter 'props' implicitly has an 'any' type
正文从这开始~ 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an ...
- React报错之Parameter 'event' implicitly has an 'any' type
正文从这开始~ 总览 当我们不在事件处理函数中为事件声明类型时,会产生"Parameter 'event' implicitly has an 'any' type"错误.为了解决 ...
- 解决TS报错Property 'style' does not exist on type 'Element'
在使用queryselector获取一个dom元素,编译时却报错说property 'style' does not exist on type 'element'. 原因:这是typescript的 ...
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- elasticsearch查询:启动项目报错No property ... found for...Did you mean '...'?
网上找的案例是: 实体类字段定义:private String sku_no;dao中接口名定义:Goods findBySkuNo(String skuNo);spring-data按照接口方法定义 ...
- react中使用typescript时,error: Property 'setState' does not exist on type 'Home'
问题描述: 我在react中用typescript时,定义一个Home组件,然后在组件里用setState时会有这样一个报错:(如图)Property 'setState' does not exis ...
- notification 报错the method build() is undefined for the type Notificatin.Builder
notification 报错the method build() is undefined for the type Notificatin.Builder 这事api版本号太低导致的 Notifi ...
随机推荐
- Wireshark学习笔记(二)取证分析案例详解
@ 目录 练习一:分析用户FTP操作 练习二:邮件读取 练习三:有人在摸鱼? 练习一:分析用户FTP操作 已知抓包文件中包含了用户登录FTP服务器并进行交互的一个过程,你能否通过wireshark分析 ...
- 【Redis】集群数据迁移
Redis通过对KEY计算hash,将KEY映射到slot,集群中每个节点负责一部分slot的方式管理数据,slot最大个数为16384. 在集群节点对应的结构体变量clusterNode中可以看到s ...
- 适配抖音!三角面转换和3d模型体量减小,轻量化一键即可完成!
抖音3d特效,可谓是越来越火爆了,这个有着迪士尼画风的3D大眼,就刷屏了国内外用户的首页! 有人好奇这些特效究竟是怎么制作的?其实就是把3D模型调整适配到头部模型上,调整位置或者大小就可以制作出一个简 ...
- Python基础学习_03
程序的流程控制 1.程序的组织结构 (1)顺序结构 (2)选择结构 (3)循环结构 2.对象的布尔值 以下对象的布尔值为False False,数值0,None,空字符串,空列表,空元组,空字典,空集 ...
- 关于个人项目(臻美MV【仿抖音App】)滑动切换视频的分析(前端角度)
我们知道你天天刷抖音的时候可以上滑切换视频,互不影响.那么我们站在前端的角度能否可以实现这种效果呢?这是我的个人项目:臻美MV 下面我是用Vue写的,现在我把它开源. Vue: 初始界面 <te ...
- linux中CentOS配置文件编辑错误撤回
未编辑状态下 U键 撤销 DD 快速删除
- rxjava回调地狱-kotlin协程来帮忙
本文探讨的是在tomcat服务端接口编程中, 异步servlet场景下( 参考我另外一个文章),用rxjava来改造接口为全流程异步方式 好处不用说 tomcat的worker线程利用率大幅提高,接口 ...
- ooday01类_对象_访问成员
笔记: 什么是类?什么是对象? 现实生活中是由很多很多对象组成的,基于对象抽出了类 对象:软件中真实存在的单个个体/东西 类:类别/类型,代表一类个体 类是对象的模子,对象是类的具体的实例 类中可以包 ...
- 浅析golang shellcode加载器
最近也是学习了一下有关shellcode进程注入的操作,简单分享一下通过golang进行实现shellcode加载器的免杀思路. 杀软的查杀方式 静态查杀:查杀的方式是结合特征码,对文件的特征段如Ha ...
- 当我们进行性能优化,我们在优化什么(LightHouse优化实操)
好的互联网产品不仅仅在功能上要高人一筹,在性能层面也需要出类拔萃,否则金玉其外败絮其中,页面是美轮美奂了,结果首屏半天加载不出来,难免让用户乘兴而来,败兴而归. 幸运的是,前端的性能优化有诸多有迹可循 ...