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

React TypeScript: No warnings or errors are thrown for possibly undefined value in array state

I have an array state in React with TypeScript that contains object items. The array state is initialized to an emtpy array. However, TypeScript in VSCode doesn’t throw any warnings or error when I try to reference an element in the array.

type Data = {
  field: string;
}[];

const [data, setData] = useState<Data>([]);

const clonedData: Data = [...data]; // Clone the data state
const firstData = clonedData[0];

const firstDataField = firstData.field; // Allowed to index, TS does not throw any warnings or errors that `firstData` may be undefined

Does anyone what is the issue? Is there a field in tsconfig.json that supresses the TS warnings?

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 :

The issue is that Typescript will always assume your index is within bounds, and as such firstData will definitely have the type {field: string}.

What you are looking for is --noUncheckedIndexedAccess

https://github.com/microsoft/TypeScript/issues/13778

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

Here is a Playground that will show you the error as you want it.

Object is possibly ‘undefined’.(2532)

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