正文从这开始~

总览

当我们试图访问一个类型为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. Java开发学习(三)----Bean基础配置及其作用范围

    一.bean基础配置 对于bean的基础配置如下 <bean id="" class=""/> 其中,bean标签的功能.使用方式以及id和clas ...

  2. Eclipse历史版本下载和选择对应的java版本

    下载Eclipse 官网: https://www.eclipse.org/ 直达 直接进入连接:https://www.eclipse.org/downloads/packages/installe ...

  3. RPA应用场景-营业收入核对

    场景概述营业收入核对 所涉系统名称 SAP ,Excel,门店业务系统 人工操作(时间/次) 4 小时 所涉人工数量 6 操作频率每日 场景流程 1.每日13点起进入SAP查询前一日营业收入记账情况: ...

  4. vmware修改虚拟机网卡mac地址

    选中"虚拟机" 右键 "设置",然后选中"网络适配器",然后点击"高级",设置"MAC地址"

  5. colab解压.tar.gz文件指令

    !tar -zxvf flower_photos.tar.gz 成功后如图:

  6. 服务器宕机了,Kafka 消息会丢失吗?

    大家好,我是树哥. 消息队列可谓是高并发下的必备中间件了,而 Kafka 作为其中的佼佼者,经常被我们使用到各种各样的场景下.随着 Kafka 而来得,还有三个问题:消息丢失.消息重复.消息顺序.今天 ...

  7. C#(.net) 面试题

    1.ASP.NET的页面生存周期 .aspx/.ashx->IIS->Asp.net_isapi.dll->HttpRuntime.ProcessRequest() ->Htt ...

  8. 串口应用:遵循uart协议,发送多个字节的数据(状态机)

    上一节中,我们遵循uart协议,它发送一次只能发送6/7/8位数据,我们不能随意更改位数(虽然在代码上可行),不然就不遵循uart协议了,会造成接收端无法接收. 在现实生活中,我们有时候要发的数据不止 ...

  9. efcore在Saas系统下多租户零脚本分表分库读写分离解决方案

    efcore在Saas系统下多租户零脚本分表分库读写分离解决方案 ## 介绍 本文ShardinfCore版本x.6.0.20+ 本期主角: - [`ShardingCore`](https://gi ...

  10. qbxt五一数学Day2

    目录 1. 判断素数(素性测试) 1. \(O(\sqrt n)\) 试除 2. Miller-Rabin 素性测试 * 欧拉函数 2. 逆元 3. exgcd(扩展欧几里得) 4. 离散对数(BSG ...