When the array is empty, TS does no type checking
My code here
type List = { name: string }[]
const l: List = []
// error
l[0].name
Is there any way to make TS check?How do I make TS check work?
>Solution :
Enable noUncheckedIndexedAccess in compilerOptions in your tsconfig.json.
After this you will start getting TS errors like Object is possibly 'undefined'.(2532) on such statements.
type List = { name: string }[]
const l: List = []
l[0].name // <-- error
l[0]?.name // <-- no error (ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
Note that noUncheckedIndexedAccess option doesn’t check the length of your array; it basically keeps reminding you that the index you are trying to access may not exist.
If your array (and its elements) are meant to be read only, you can also use const assertion:
const l = [{ name: 'foo' }] as const
l[0].name // no error
l[1].name // error: Tuple type 'readonly [{ readonly name: "foo"; }]' of length '1' has no element at index '1'.