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

Time:02-12

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?

CodePudding user response:

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)

  • Related