繁体   English   中英

元素隐式具有“any”类型,因为“number”类型的表达式不能用于索引类型“{}”

[英]Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'

我正在使用 useRef,并访问其子元素。

我收到这个错误。

元素隐式具有 'any' 类型,因为类型 'number' 的表达式不能用于索引类型 '{}'。 在类型“{}”上找不到带有“数字”类型参数的索引签名

代码是

const subCnt = useRef<HTMLDivElement>();

useEffect(()=>{

    if (!(subCnt.current?.children?.length! > 0)) return

    let lastChild: ReactNode = subCnt.current?.children;
    lastChild = lastChild[lastChild?.length - 1]; //Getting the error here
    ...
})

我收到错误的lastChild = lastChild[lastChild?.length - 1];行是 at lastChild = lastChild[lastChild?.length - 1];

为什么会显示这个错误?

你的实际错误是在线之前:

 let lastChild: ReactNode = subCnt.current?.children;

我不知道为什么 TypeScript 没有抱怨,显然这些类型非常兼容,但它们真的不应该。 该类型的.childrenHTMLCollection -它包含了所有的孩子,不仅是最后一个,所以这个名字被混淆为好。

正确的做法是

useEffect(() => {
    const children: HTMLCollection | undefined = subCnt.current?.children;
    if (!children?.length) return;

    const lastChild: Element = children[children.length - 1];
    …
})

但您实际上可以通过直接使用.lastElementChild来简化它:

useEffect(() => {
    const lastChild: Element | undefined = subCnt.current?.lastElementChild;
    if (!lastChild) return;
    …
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM