If I have an array of arrays, then it isn't safe to blindly do
const a = array[index1][index2]
since array[index1]
could be undefined
, leading to an error. What I expected to occur when I defended with const a = array[index1]?.[index2]
was to have a
be a union type with undefined
. That's not what I get, though- I see it as the type of the underlying array.
How do I defend in code such that TS can pick up the potential for undefined
at compile time?
MCVE:
type A = {
owner?: string,
feline?: string
}
const arr: Array<Array<A>> = []
const item = arr[2]?.[5]; // typed as A rather than A|undefined