2

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

1 Answer 1

5

in your tsConfig option, add this line

{
"compilerOptions":{
   //... something else
   "noUncheckedIndexedAccess": true
 }
}

https://devblogs.microsoft.com/typescript/announcing-typescript-4-1/#checked-indexed-accesses-nouncheckedindexedaccess

https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess

enter image description here

enter image description here

playground

1
  • 1
    How is this not the default!?
    – Evanss
    Commented May 1, 2024 at 10:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.