如何处理TypeScript报错:'node' is possibly 'null'?
Got it, let's sort out this TypeScript error you're facing. The root cause is that Testing Library's MatcherFunction type defines the node parameter as potentially null—since matchers can run against elements that might not exist yet. TypeScript is correctly flagging that you're trying to access properties like .children on a value that could be null.
Here are two safe, idiomatic ways to fix this:
1. Add a Null Guard Clause (Recommended)
The cleanest approach is to check if node is null at the start of your matcher and return early if it is. This tells TypeScript that node is definitely an Element for the rest of the 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) => { // Add this guard clause to handle null case if (!node) return false; const childrenDontHaveText = Array.from(node.children).every( (child) => !hasText(child) ) return hasText(node) && childrenDontHaveText }) }
This is the best practice because it's safe (prevents runtime errors if node is null) and TypeScript can properly infer the type of node after the check.
2. Use Non-Null Assertion (Only If You're Certain Node Won't Be Null)
If you're absolutely sure that node will never be null when this matcher runs (e.g., your query is guaranteed to find an element), you can use the non-null assertion operator (!) to tell TypeScript to ignore the null possibility. However, this is risky—if node ever is null, it will cause a runtime error:
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( // Add ! here (child) => !hasText(child) ) return hasText(node!) && childrenDontHaveText // And here }) }
Stick with the guard clause unless you have a specific reason to use the non-null assertion—safety first!
内容的提问来源于stack exchange,提问作者user3142695

