gpt4 book ai didi

reactjs - typescript + useRef : Type X is not assignable to type Y

转载 作者:行者123 更新时间:2023-12-03 23:42:25 32 4
gpt4 key购买 nike

这个简单的组件:

const Editable = ({multiline}: { multiline: boolean }) => {
const ref = useRef<HTMLInputElement|HTMLTextAreaElement>(null);
return <div>
{multiline ? <textarea ref={ref}/> : <input ref={ref}/>}
</div>
}
有以下 typescript 错误:
Error:(7, 32) TS2322: Type 'RefObject<HTMLInputElement | HTMLTextAreaElement>' is not assignable to type 'string | ((instance: HTMLTextAreaElement | null) => void) | RefObject<HTMLTextAreaElement> | null | undefined'.
Type 'RefObject<HTMLInputElement | HTMLTextAreaElement>' is not assignable to type 'RefObject<HTMLTextAreaElement>'.
Type 'HTMLInputElement | HTMLTextAreaElement' is not assignable to type 'HTMLTextAreaElement'.
Type 'HTMLInputElement' is missing the following properties from type 'HTMLTextAreaElement': cols, rows, textLength, wrap
Error:(7, 53) TS2322: Type 'RefObject<HTMLInputElement | HTMLTextAreaElement>' is not assignable to type 'string | ((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined'.
Type 'RefObject<HTMLInputElement | HTMLTextAreaElement>' is not assignable to type 'RefObject<HTMLInputElement>'.
Type 'HTMLInputElement | HTMLTextAreaElement' is not assignable to type 'HTMLInputElement'.
Type 'HTMLTextAreaElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, checked, and 23 more.
使用以下行可以忽略错误:
const ref = useRef<any>(null);
怎么可以 useRef使用正确的类型并且没有错误?

最佳答案

解决方案1:Type assertion

const ref = useRef<HTMLInputElement | HTMLTextAreaElement>(null);
return (
<div>
{multiline ? <textarea ref={ref as React.RefObject<HTMLTextAreaElement>}/>:
<input ref={ref as React.RefObject<HTMLInputElement>} />}
</div>
)
<textarea ... />期待 ref需要 HTMLTextAreaElement . HTMLTextAreaElement包含 different properties than HTMLInputElement ,所以 supertype HTMLTextAreaElement | HTMLInputElement不能分配给其中一个节点。类型断言在这里完全没问题。优点:我们被迫缩小 ref以类型安全的方式。缺点:类型断言有点冗长。
解决方案 2: Intersection type引用
const ref = useRef<HTMLInputElement & HTMLTextAreaElement>(null);
return (
<div>
{multiline ? <textarea ref={ref } /> :
<input ref={ref} />}
</div>
)
这有效,如 HTMLInputElementHTMLTextAreaElement不要有冲突的属性类型(否则会导致 never )。优点:更紧凑的代码。缺点:确保之前缩小元素。例如。您也许可以为 HTMLInputElement 调用以下代码导致运行时错误:
ref.current && ref.current.cols // input does not have cols
Playground

关于reactjs - typescript + useRef<X|Y> : Type X is not assignable to type Y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64951243/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com