When working with arrays in TypeScript, the type inference can be tricky due to elements changing at runtime. In this case, to ensure proper type inference for the data array as Array<{ name: string }>
, you need to explicitly set the type of the data
array as readonly
. By doing so, TS can correctly infer the type for the first element inside the data array as {name: "hi"}
.
To resolve this issue, simply include as const
after the definition of the data array.
const data = [
{name: "hi"}
] as const;
// By adding 'as const', TS will infer the type for data as readonly[{ readonly name: "hi";}]
For a demonstration, you can view the example in TypeScript playground