【问题标题】:Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引类型“{}”
【发布时间】:2021-12-20 06:31:20
【问题描述】:

我正在使用 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];

为什么会出现这个错误?

【问题讨论】:

  • 它告诉您缺少空检查,如果空检查,则放置一个,这应该会消失
  • @vaira 我试过了。 lastChild![lastChild!?.length! - 1] 甚至 lastChild ? lastChild[lastChild?.length - 1] : undefined 还是不行。
  • if(lastChind) {lastChild = lastChild[lastChild?.length - 1];}
  • 而不是 ReactNode 使用类型 HTMLCollection
  • 对 React 了解不多,但 ReactNode 被定义为 Iterable,这可能就是为什么它甚至不会抱怨您将 lastChild 键入为 ReactNode 而不是 @987654327 @。但是你不能在Iterable 上做[index]。这就是你错误的根源。你可以先做Array.from(lastChild),然后再做[]。但我认为只使用两个变量而不是一个变量并使用 HTMLCollection 而不是 ReactNode 会更好。

标签: javascript reactjs typescript


【解决方案1】:

你的实际错误就在前面:

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

我不知道为什么 TypeScript 不抱怨,显然这些类型奇怪地兼容,但他们真的不应该。 .children 的类型是 HTMLCollection - 它包含所有孩子,不仅是最后一个,所以名字也很混乱。

正确的做法是

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

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

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

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

【讨论】:

  • 感谢您的解释。但我无法从 lastChild 访问像 .offsetLeft 这样的属性。在您的两个实现中。它说Property 'offsetLeft' does not exist on type 'Element'.ts(2339)
  • 啊,对,是HTMLElement.offsetLeft
  • 谢谢,lastElementChildElement 类型,最后也需要类型断言,当我也使用 subCnt.current?.lastElementChild as HTMLElement 时它也有效
猜你喜欢
  • 2021-03-17
  • 2022-01-04
  • 2021-04-20
  • 1970-01-01
  • 2020-11-13
  • 2019-12-17
  • 2020-10-29
  • 2020-10-04
  • 2019-12-15
相关资源
最近更新 更多