'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 allows setting of this particular TS warning?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source