[英]Property 'click' does not exist on type 'never'. TS2339
According to other similar issues about this type of error with TypeScript (on questions #44147937 and #40796374 ) I've found that assigning null
to create a state or reference will cause this problem: Property ... does not exist on type 'never'
根据关于 TypeScript 此类错误的其他类似问题(关于问题#44147937和#40796374 ),我发现分配
null
来创建状态或引用会导致此问题: Property ... does not exist on type 'never'
how to handle this issue in this example component?如何在此示例组件中处理此问题?
const FooComponent: FunctionComponent<FooInterface> = () => {
const myRef = useRef(null)
const handleClickOnButton = () => myRef?.current?.click();
return (
<div>
<div ref={myRef} />
<button onClick={handleClickOnButton} />
</div>
}
TypeScript can't infer the type of the ref from where you use it later in the code, you have to tell it the type of the ref: TypeScript 无法从您稍后在代码中使用它的位置推断 ref 的类型,您必须告诉它 ref 的类型:
const ref = useRef<HTMLDivElement>(null);
// −−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^
( useRef
adds the null
type to the type parameter you give it, soyou don't have to use <HTMLDivElement | null>
.) (
useRef
将null
类型添加到您提供的类型参数中,因此您不必使用<HTMLDivElement | null>
。)
I've found a way to solve this problem.我找到了解决这个问题的方法。
giving <HTMLAnchorElement>
to useRef will fix this issue:将
<HTMLAnchorElement>
赋予 useRef 将解决此问题:
const linkRef = useRef<HTMLAnchorElement>(null);
Important : I have to use null to create this type of ref to passing into an element so can't change it.重要提示:我必须使用 null 来创建这种类型的 ref 以传递给元素,因此无法更改它。
Important : assigning <HTLMDivElement>
or <HTMLElement>
will cause another error:重要提示:分配
<HTLMDivElement>
或<HTMLElement>
将导致另一个错误:
TS2322: Type 'RefObject' is not assignable to type 'Ref | TS2322:类型“RefObject”不可分配给类型“Ref | undefined'.
不明确的'。 Type 'RefObject' is not assignable to type 'RefObject'.
类型“RefObject”不可分配给类型“RefObject”。 Type 'HTMLElement' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 21 more.
“HTMLElement”类型缺少“HTMLAnchorElement”类型中的以下属性:字符集、坐标、下载、hreflang 等 21 个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.