正文从这开始~

总览

当我们试图访问一个类型为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'的更多相关文章

  1. React报错之Property 'X' does not exist on type 'HTMLElement'

    正文从这开始~ 总览 在React中,当我们试图访问类型为HTMLElement 的元素上不存在的属性时,就会发生Property 'X' does not exist on type 'HTMLEl ...

  2. React报错之Property 'value' does not exist on type EventTarget

    正文从这开始~ 总览 当event参数的类型不正确时,会产生"Property 'value' does not exist on type EventTarget"错误.为了解决 ...

  3. React报错之Parameter 'props' implicitly has an 'any' type

    正文从这开始~ 总览 当我们没有为函数组件或者类组件的props声明类型,或忘记为React安装类型声明文件时,会产生"Parameter 'props' implicitly has an ...

  4. React报错之Parameter 'event' implicitly has an 'any' type

    正文从这开始~ 总览 当我们不在事件处理函数中为事件声明类型时,会产生"Parameter 'event' implicitly has an 'any' type"错误.为了解决 ...

  5. 解决TS报错Property 'style' does not exist on type 'Element'

    在使用queryselector获取一个dom元素,编译时却报错说property 'style' does not exist on type 'element'. 原因:这是typescript的 ...

  6. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  7. elasticsearch查询:启动项目报错No property ... found for...Did you mean '...'?

    网上找的案例是: 实体类字段定义:private String sku_no;dao中接口名定义:Goods findBySkuNo(String skuNo);spring-data按照接口方法定义 ...

  8. react中使用typescript时,error: Property 'setState' does not exist on type 'Home'

    问题描述: 我在react中用typescript时,定义一个Home组件,然后在组件里用setState时会有这样一个报错:(如图)Property 'setState' does not exis ...

  9. notification 报错the method build() is undefined for the type Notificatin.Builder

    notification 报错the method build() is undefined for the type Notificatin.Builder 这事api版本号太低导致的 Notifi ...

随机推荐

  1. 渗透测试之sql注入验证安全与攻击性能

    由于渗透测试牵涉到安全性以及攻击性,为了便于交流分享,本人这里不进行具体网址的透露了. 我们可以在网上查找一些公司官方网站如(http://www.XXXXXX.com/xxxx?id=1) 1.拿到 ...

  2. 从零打造一个Web地图引擎

    说到地图,大家一定很熟悉,平时应该都使用过百度地图.高德地图.腾讯地图等,如果涉及到地图相关的开发需求,也有很多选择,比如前面的几个地图都会提供一套js API,此外也有一些开源地图框架可以使用,比如 ...

  3. 【微服务专题之】.Net6下集成消息队列上-RabbitMQ

    ​ 微信公众号:趣编程ACE关注可了解更多的.NET日常实战开发技巧,如需源码 请公众号后台留言 源码;[如果觉得本公众号对您有帮助,欢迎关注] .Net中RabbitMQ的使用 [微服务专题之].N ...

  4. NC14683 储物点的距离

    NC14683 储物点的距离 题目 题目描述 一个数轴,每一个储物点会有一些东西,同时它们之间存在距离. 每次给个区间 \([l,r]\) ,查询把这个区间内所有储物点的东西运到另外一个储物点的代价是 ...

  5. vmstate 命令详解2022

    vmstat 是一个查看虚拟内存(Virtual Memory)使用状况的工具,但是怎样通过 vmstat 来发现系统中的瓶颈呢? 1. 使用vmstat 使用前我们先看下命令介绍及参数定义 Usag ...

  6. P2599 [ZJOI2009]取石子游戏 做题感想

    题目链接 前言 发现自己三岁时的题目都不会做. 我发现我真的是菜得真实. 正文 神仙构造,分讨题. 不敢说有构造,但是分讨我只服这道题. 看上去像是一个类似 \(Nim\) 游戏的变种,经过不断猜测结 ...

  7. Tapdata 肖贝贝:实时数据引擎系列(四)-关于 Oracle 与 Oracle CDC

      摘要:想实现 Oracle 的 CDC,排除掉一些通用的比如全量比对, 标记字段获取之外, 真正的增量形式获取变更, 有三种办法: Logminer .XStream .裸日志解析,但不管哪种方法 ...

  8. 跨模态语义关联对齐检索-图像文本匹配(Image-Text Matching)

    论文介绍:Negative-Aware Attention Framework for Image-Text Matching (基于负感知注意力的图文匹配,CVPR2022) 代码主页:https: ...

  9. Object类和toString方法 --和Object类的equals方法

    一,Object类概述:Object是类层次结构的根,每个类都可以将Object作为超类,所有类都直接或者间接的继承自该类构造方法:pulic Object()在面向对象中,子类要访问父类的无参构造方 ...

  10. eclipse调用MySQL数据库的方法

    今天来总结一下使用如何使用eclipse调用MySQL数据库的数据. 一.设置eclipse 我们首先来设置一下eclipse. 在下部的Servers中右键选择new,选择server 之后在新弹出 ...