Despite understanding the correct syntax, the code remains puzzling to me.
The use of optional chaining in the provided code ensures that the result of
myArray.filter(x => x.testKey === myTestKey)
is neither
null
nor
undefined
, as confirmed by the TypeScript output. However, this precaution may not be necessary since the result of the
filter
method always yields an
array
. JavaScript does not throw "Array bounds exceeded" errors, thus accessing any index will simply return
undefined
if the element does not exist.
For further clarity, consider the following examples:
const myArray: string[] = undefined
console.log(myArray.filter(x => x)?.[0]) //throws Cannot read property 'filter' of undefined
// In this instance, the optional chaining protects against an undefined array
const myArray: string[] = undefined
console.log(myArray?.filter(x => x)[0]) //outputs "undefined"