【问题标题】:Argument of type 'Element | null' is not assignable to parameter of type 'Element | VirtualElement''Element | 类型的参数null' 不可分配给“元素 |”类型的参数虚拟元素'
【发布时间】:2021-09-09 18:54:29
【问题描述】:

我在尝试使用 popper 组件时遇到以下错误,只是在努力理解如何正确键入它。文档不清楚,我也没有太多 Typescript 经验。

'Element | 类型的参数null' 不可分配给“元素 |”类型的参数虚拟元素'。 类型 'null' 不能分配给类型 'Element |虚拟元素'.ts(2345) 常量爆米花:元素 |空

const popcorn = document.querySelector('#popcorn')
const tooltip = document.querySelector('#tooltip')

createPopper(popcorn, tooltip, {
  placement: 'top',
})

【问题讨论】:

  • 由于您使用querySelector() 搜索的元素可能不存在(就编译器 而言),它的返回类型自然是Element | null 而不仅仅是Element。而且,createPopper() 显然不接受 null 参数,因此它不会接受可能为 null 的 Element | null。如果确定元素存在,那么你可以在第一行和第二行使用the non-null assertion operator,这会将类型强制转换为Element

标签: reactjs typescript


【解决方案1】:

createPopper 函数希望确保 popcorntooltip 都是元素。由于querySelector 可以返回null(如果不存在任何元素),只需检查以确保popcorntooltip 不为空,然后再调用createPopper

const popcorn = document.querySelector('#popcorn')
const tooltip = document.querySelector('#tooltip')

if (popcorn && tooltip) {
  createPopper(popcorn, tooltip, { placement: 'top' })
}

【讨论】:

  • 非常感谢这位尼克。这就说得通了。不过还有一件事。我没有在“工具提示”上收到类型错误哈哈。 “元素”类型的参数不能分配给“HTMLElement”类型的参数。 'Element' 类型缺少 'HTMLElement' 类型的以下属性:accessKey、accessKeyLabel、autocapitalize、dir 和 107 more.ts(2345) 想知道您是否也能解释一下这个?谢谢老哥
  • 我对为什么没有很好的答案,但它是looks like getElementById returns a type HTMLElement,比Element 窄。所以我建议将你的第二行改为const tooltip = document.getElementById('tooltip')
【解决方案2】:
const popcorn = document.querySelector<HTMLDIVElemnt>('#popcorn')
const tooltip = document.querySelector<HTMLDIVElemnt>('#tooltip')

if (popcorn && tooltip) {
  createPopper(popcorn, tooltip, { placement: 'top' })
}

如果目标是按钮,请使用&lt;HTMLButtonELement&gt;
这应该可以解决您的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2022-08-17
    相关资源
    最近更新 更多