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 ...
随机推荐
- CabloyJS的微信API对接模块:当前支持微信公众号和微信小程序
Cabloy-微信是什么 Cabloy-微信是基于CabloyJS全栈业务开发框架开发的微信接口模块,当前整合了微信公众号和微信小程序的接口,达到开箱即用的使用效果.在Cabloy-微信的基础上,可以 ...
- Linux Cgroup v1(中文翻译)(4):Block IO Controller
Block IO Controller 1 概览 cgroup子系统blkio实现了block io控制器.无论是对存储结构上的叶子节点和还是中间节点,它对各种IO控制策略(proportional ...
- Java创建数据库新建表及初始化表
方法一 package com.crt.openapi; import java.sql.DriverManager;import java.sql.ResultSet;import java.io. ...
- HMS Core新闻行业解决方案:让技术加上人文的温度
开发者们,你希望用户如何获取新闻? 有的人靠手机弹窗知天下事,有的人则在新闻应用中尽览每一篇文章:有的人一目十行,有的人则喜欢细细咀嚼:有的人主动探索,有的人则想要应用投其所好. 科技在不断刷新着用户 ...
- Spring框架系列(8) - Spring IOC实现原理详解之Bean实例化(生命周期,循环依赖等)
上文,我们看了IOC设计要点和设计结构:以及Spring如何实现将资源配置(以xml配置为例)通过加载,解析,生成BeanDefination并注册到IoC容器中的:容器中存放的是Bean的定义即Be ...
- 毕业论文着急了?Python疫情数据分析,并做数据可视化展示
采集流程 一..明确需求 采集/确诊人数/新增人数 二.代码流程 四大步骤 发送请求 获取数据 网页源代码 解析数据 筛选一些我想用的数据 保存数据 保存成表格 做数据可视化分析 开始代码 1. 发送 ...
- Set集合转换为List集合
举个栗子,看图:
- 漫谈客户端存储技术之Cookie篇
Cookie 说到Cookie,不管作为前端开发人员还是后端开发人员并不陌生,作为一种最古老.最稳定的客户端存储形式,即便是在当下各种新的客户端存储技术层出不穷的时代,它仍旧有其一席之位.Cookie ...
- Map接口中的常用方法和Map集合遍历键找值方式
Map接口中定义了很多方法,常用的如下: public V put(K key,V value) 将指定的值与此映射中的指定键相关联(可选操作) V remove(Object key); 如果此映射 ...
- 初次使用 eolink 感受
最近总有前端小伙伴来找我抱怨,"后端接口出来太晚,影响我的任务进度"."后端接口改了也不通知我一下,到冒烟测试的时候报一堆的错".我拉后端小伙伴了解情况,结果问 ...