正文从这开始~

总览

在React中,当我们试图访问类型为HTMLElement 的元素上不存在的属性时,就会发生Property 'X' does not exist on type 'HTMLElement'错误。为了解决该错误,在访问属性之前,使用类型断言来正确地类型声明元素。

这里有三个例子来展示错误是如何发生的。

// App.tsx

import {useEffect} from 'react';

export default function App() {
useEffect(() => {
const input = document.getElementById('first_name');
// ️ Property 'value' does not exist on type 'HTMLElement'.ts(2339)
console.log(input?.value); // ----------------------------------------------------------------- const link = document.getElementById('link');
// ️ Property 'href' does not exist on type 'HTMLElement'.ts(2339)
console.log(link?.href); // ----------------------------------------------------------------- const button = document.getElementById('btn');
if (button != null) {
// ️ Property 'disabled' does not exist on type 'HTMLElement'.ts(2339)
button.disabled = true;
}
}, []); return (
<div>
<input
id="first_name"
type="text"
name="first_name"
defaultValue="Initial Value"
/> <a id="link" href="<https://google.com>" target="_blank" rel="noreferrer">
Open Google
</a> <button id="btn">Submit</button>
</div>
);
}

产生错误的原因是,document.getElementById方法的返回类型是HTMLElement | null,但是我们试图访问的属性不存在于HTMLElement 类型。

类型断言

为了解决这个错误,使用类型断言来为元素正确地进行类型声明。比如说,类型断言为HTMLInputElementHTMLButtonElementHTMLAnchorElementHTMLImageElementHTMLDivElementHTMLTextAreaElement等等。这取决于你所处理的元素。

这些类型始终命名为HTML***Element 。一旦你开始输入HTML…,你的IDE将会帮你自动补全。

import {useEffect} from 'react';

export default function App() {
useEffect(() => {
// type elements correctly via type assertions
const input = document.getElementById('first_name') as HTMLInputElement;
console.log(input?.value); const link = document.getElementById('link') as HTMLAnchorElement;
console.log(link?.href); const button = document.getElementById('btn') as HTMLButtonElement;
if (button != null) {
button.disabled = true;
}
}, []); return (
<div>
<input
id="first_name"
type="text"
name="first_name"
defaultValue="Initial Value"
/> <a id="link" href="<https://google.com>" target="_blank" rel="noreferrer">
Open Google
</a> <button id="btn">Submit</button>
</div>
);
}

类型断言被用于我们知道值的类型信息,但是TypeScript却不知道的时候。

我们明确的告诉TypeScript,input变量上存储了HTMLInputElement ,并让TS不要担心。

同样的,我们将link变量类型声明为HTMLAnchorElement,将btn变量类型声明为HTMLButtonElement

你可以在访问一个属性之前,内联使用类型断言。

import {useEffect} from 'react';

export default function App() {
useEffect(() => {
const value = (document.getElementById('first_name') as HTMLInputElement).value;
console.log(value);
}, []); return (
<div>
<input
id="first_name"
type="text"
name="first_name"
defaultValue="Initial Value"
/> <a id="link" href="<https://google.com>" target="_blank" rel="noreferrer">
Open Google
</a> <button id="btn">Submit</button>
</div>
);
}

如果你只需要访问属性一次,并且不希望将元素分配给变量,那么内联类型声明可以完成这项工作。

如果你想更精确地处理元素的类型,可以使用联合类型将类型声明为HTML***Element | null

import {useEffect} from 'react';

export default function App() {
useEffect(() => {
const input = document.getElementById(
'first_name',
) as HTMLInputElement | null;
console.log(input?.value); const link = document.getElementById('link') as HTMLAnchorElement | null;
console.log(link?.href); const button = document.getElementById('btn') as HTMLButtonElement | null;
if (button != null) {
button.disabled = true;
}
}, []); return (
<div>
<input
id="first_name"
type="text"
name="first_name"
defaultValue="Initial Value"
/> <a id="link" href="<https://google.com>" target="_blank" rel="noreferrer">
Open Google
</a> <button id="btn">Submit</button>
</div>
);
}

HTML***Element 或者null 类型是最准确的类型,因为如果DOM元素上不存在id属性,那么document.getElementById()将会返回null

你可以使用可选链操作符(?.)在访问属性之前来进行短路运算,如果引用是空值(null或者undefined)的话。

或者,你可以使用简单的if语句作为类型守卫,就像我们对button处理的那样。

总结

最佳实践是在类型断言中包含null 。因为如果元素上面不提供id属性,那么getElementById方法将会返回null

React报错之Property 'X' does not exist on type 'HTMLElement'的更多相关文章

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

    正文从这开始~ 总览 当我们试图访问一个类型为HTMLElement的元素上的value属性时,会产生"Property 'value' does not exist on type 'HT ...

  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. 133_Power BI 报表服务器2020年1月版本更新亮点

    博客:www.jiaopengzi.com 焦棚子的文章目录 请点击下载附件 一个很长的春节假期后,居家办公. 升级了Power BI 报表服务器(2020年1月版本). 具体的升级内容见官网博客: ...

  2. 实践torch.fx第一篇——基于Pytorch的模型优化量化神器

    第一篇--什么是torch.fx 今天聊一下比较重要的torch.fx,也趁着这次机会把之前的torch.fx笔记整理下,笔记大概拆成三份,分别对应三篇: 什么是torch.fx 基于torch.fx ...

  3. cut-列过滤

    列过滤命令. 语法 cut [选项] 要过滤的字符串 选项 -f 以字段为单位进行分割 -c 以字符为单位进行分割 -b 以字节为单位进行分割 -d 以分割符为单位进行分割,分隔符可以是"冒 ...

  4. [漏洞复现] [Vulhub靶机] OpenSSL Heartbleed Vulnerability (CVE-2014-0160)

    免责声明:本文仅供学习研究,严禁从事非法活动,任何后果由使用者本人负责. 0x00 背景知识 传输层安全协议SSL 安全套接字协议SSL(Secure Sockets Layer),及其继任者传输层安 ...

  5. .net6.0 中一个接口多个实现的服务注册与注入

    1.现有一个数据库操作接口 如下   它有两个数据操作实现 Sqlserver 和MySql的数据库操作实现类 现在我们需要 将这个两个类 注册到MVC中 注意这里注册的服务类型都是 IDataBas ...

  6. SpringCloud 服务治理

    目录 1. Eureka 1.1 Eureka 介绍 1.2 Eureka 快速入门 父工程 Eureka Server(子工程) pom.xml 启动类 application.yml Eureka ...

  7. 『忘了再学』Shell基础 — 26、cut列提取命令

    目录 1.cut命令说明 2.cut命令练习 (1)cut命令基本用法 (2)cut命令选取多列 (3)按字符来进行提取 (4)按指定分隔符进行截取数据 3.cut命令分隔符说明 1.cut命令说明 ...

  8. 15.LNMP架构的源码编译

    LNMP架构的源码编译 目录 LNMP架构的源码编译 编译安装 Nginx 服务 1.关闭防火墙 2.安装相关依赖包 3.创建运行用户 4.解压软件包及配置编译安装 5.优化路径 6.将Nginx 加 ...

  9. Bika LIMS 开源LIMS集—— SENAITE的安装

    安装环境 操作系统 Ubuntu 18.04 LTS Python 2.x. Plone 4 安装步骤 Ubuntu等Linux.Mac系统一般安装有Python的环境,但由于需要安装Python扩展 ...

  10. 南京大学 静态软件分析(static program analyzes)-- introduction 学习笔记

    一.Programming Languages体系 静态程序分析是编程语言中应用层面下的一个细分领域,它是一个非常重要的核心内容. 在理论部分,考虑的是如何设计一个语言的语法和语义,如何设计语言的类型 ...