Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript does no type checking When the array is empty

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

Playground

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'.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading