正文从这开始~

总览

当我们试图访问一个类型为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. 【python】tile函数简单介绍

    转:https://blog.csdn.net/april_newnew/article/details/44176059格式:tile(A,reps)* A:array_like* 输入的array ...

  2. Volcano社区v1.6.0版本正式发布

    摘要:Volcano社区v1.6.0版本正式发布.此次版本增加了弹性作业管理.基于真实负载的动态调度. 基于真实负载的重调度.Volcano Job插件--MPI等多个新特性. 本文分享自华为云社区& ...

  3. 国内外组态软件对比分析(InTouch、WinCC、iFix、iNeuOS)

    在我国自动化控制领域应用较广泛的工业自动化组态软件有Wonderware公司InTouch.西门子公司Wincc.GE公司iFix.国内也有一些传统组态软件厂商,使用的功能和形式基本上十分类似,受当时 ...

  4. Python基础学习笔记_02

    Python中的运算符 标准算术运算符 加(+) 减(-) 乘(*) 除(/) 整除(//) print(1+1) #加法运算 print(1-1) #减法运算 print(2*4) #乘法运算 pr ...

  5. 一次 MySQL 误操作导致的事故,「高可用」都顶不住了!

    这是悟空的第 152 篇原创文章 官网:www.passjava.cn 你好,我是悟空. 上次我们项目不是把 MySQL 高可用部署好了么,MySQL 双主模式 + Keepalived,来保证高可用 ...

  6. UiPath邮件自动化

    在UiPath中下载Outlook电子邮件附件Outlook电子邮件自动化教程UiPathRPAhttps://www.bilibili.com/video/BV1oK411L72T 在UiPath中 ...

  7. IDEA Unicode码转中文

    1.打开设置 2.打开文件编码设置,按如图设置

  8. 从20s优化到500ms,我用了这三招

    前言 接口性能问题,对于从事后端开发的同学来说,是一个绕不开的话题.想要优化一个接口的性能,需要从多个方面着手. 其实,我之前也写过一篇接口性能优化相关的文章<聊聊接口性能优化的11个小技巧&g ...

  9. cookie、session、tooken

    一.cookie 的诞生 首先需要知道Http协议的无状态连接的,即这一次请求和上一次请求是没有任何关系的,互不认识的,没有关联的. 服务端,既不知道上一次请求和这一次请求的关联,也无法知道哪一个客户 ...

  10. Day04 HTML标记

    路径 ./ 同级目录 ./ 进入该目录名下 ../ 上一级目录 HTML标记 图片 <!-- 图片标记 src 图片的路径 width 设置图片宽度 height 设置图片高度 title 鼠标 ...