interface Data {
resultSet?: {
errors?: readonly string[] | null;
} | null;
}
async function getData(): Promise<Data|null> { return null; }
async function example() {
const data = await getData();
if ((data?.resultSet?.errors?.length ?? 0) > 0) {
// data.resultSet.errors can't be null here, as (data?.resultSet?.errors?.length ?? 0) > 0
console.error( data.resultSet.errors.join( '\n' ) );
}
}
example();
'data' is possibly 'null'.
'data.resultSet' is possibly 'null' or 'undefined'.
'data.resultSet.errors' is possibly 'null' or 'undefined'.
π Search Terms
null nullish undefined narrow if
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play/?ts=6.0.3#code/JYOwLgpgTgZghgYwgAgCJzHZBvAsAKGSOSggGcBXAGzAGUIwB+ALhwOI+WigHsoyWJCHAAmPEFQCeyMmCigA5gG0AusgA+yENSoBudsQC+GrTv35DBAnDKSQCZDAr2wwccgUN0mABQBKVgAFXgBbYDIIAB5vOHVtKioAPhwhMAooEFME3WRLfGtbe0dnBFd3CAAPOBCAByoIfzZCYgRxWWQRDCwAXmQ4AHc4YDAPLy7-cw5gGGQfH07MRgA6UkoaeiYl7j4BJfqQBTAAC2RGRmQABj9kZKumzmIAekeOrpXyajoGLahefmQEHAQAByEYAIxQ8SoyCO0AgABo+mRZgs4MtVp8NsttvxlvtDiczpdrrcDA9WiAyDx6j8-j5Xph3msvmBaTslgArHigenAgA6IOQ1z8kyMBDyBEq1TqDRFBCAA
π» Code
π Actual behavior
Errors in code
π Expected behavior
No errors
Additional information about the issue
The
ifcondition should eliminate nullish values from the body.