【问题标题】:Element is possible 'null'元素可能为 \'null\'
【发布时间】:2023-01-18 02:37:46
【问题描述】:

我确实收到此函数的打字稿错误'node' is possibly 'null'

import { MatcherFunction } from '@testing-library/react'

type Query = (f: MatcherFunction) => HTMLElement

export const withMarkup = (query: Query) => (text: string) => {
  const hasText = (node: Element) => node.textContent === text
  return query((_, node) => {
    const childrenDontHaveText = Array.from(node.children).every(
      (child) => !hasText(child)
    )
    return hasText(node) && childrenDontHaveText
  })
}

我想得到一些解释如何处理这个问题

【问题讨论】:

    标签: typescript


    【解决方案1】:

    MatcherFunction 输入为:

    (content: string, element: Element | null) => boolean
    

    这意味着当你这样做时:

    return query((_, node) => {
      //...
    })
    

    nodeElement | null 类型。如果node 可能是null,则不能执行node.children,因为那样会导致运行时崩溃。


    要修复它,您只需首先检查null

    import { MatcherFunction } from '@testing-library/react'
    
    type Query = (f: MatcherFunction) => HTMLElement
    
    export const withMarkup = (query: Query) => (text: string) => {
      const hasText = (node: Element) => node.textContent === text
      return query((_, node) => {
        if (!node) return false
        // Added this line
        
        const childrenDontHaveText = Array.from(node.children).every(
          (child) => !hasText(child)
        )
        return hasText(node) && childrenDontHaveText
      })
    }
    

    现在node.children只有在node不是null,因此永远不会在运行时崩溃。

    See Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2017-07-24
      相关资源
      最近更新 更多