I do get the typescript error 'node' is possibly 'null'
for this function:
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
})
}
I would like to get some explanation how to handle this issue
CodePudding user response:
MatcherFunction
is typed as:
(content: string, element: Element | null) => boolean
Which means that when you do:
return query((_, node) => {
//...
})
node
is of type Element | null
. And you can't do node.children
if node
might be null
, since that would cause a runtime crash.
To fix it you simply have to first check for 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
})
}
Now node.children
will only be executed if node
is not null
, and is, therefore, never going to crash at runtime.