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

Accessing an array by index won't warn about possibility of undefined?

Is there a way to make sure, that the compiler will cry every time I try to access an array by index?

In my example, I explicitly say, that the record could be undefined, but the compiler still won’t cry.

type MyDataType =  { id: number, name: string };

const array: MyDataType[] = [
    { id: 1, name: "Hey folks" },
]

const record: MyDataType | undefined = array[1];

What is the best approach to make it evident, that array[index] can return undefined or maybe even null?

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 :

Add noUncheckedIndexedAccess to your compilerOptions in your tsconfig.json file.

// tsconfig.json
{
  "compilerOptions": {
    "noUncheckedIndexedAccess": true
  }
}

Playground

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