When you do not specify a type for a value - such as the return value of your function in this case - TypeScript will attempt to infer the most precise type possible. In situations where the arrays within your returned object's sections
are always empty, TypeScript infers them as never[]
(type[]
is just an alias for Array<type>
); indicating an array that cannot hold any values. This can be observed in the code snippet below:
const functionReturningEmptyArray = () => ({ items: [] });
type EmptyArray = ReturnType<typeof functionReturningEmptyArray>;
// type EmptyArray = { items: never[] }
To address this issue, one approach is to utilize the section
interface that you have defined to explicitly define the return type of state
.
export const state = (): { sections: Array<section> } => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
The colon following the empty parentheses on the initial line declares the function's return type. I have included the object type inline in this instance since it comprises only one property. However, if your state
is more intricate or for enhanced readability, you can extract it into a distinct type and refer to that as the return type.
interface MyState {
sections: Array<section>;
}
export const state = (): MyState => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
At this juncture, TypeScript will emit an error concerning your returned value because your section
interface stipulates that the object must also possess a section_body
property, which is absent in your returned sections
array. To rectify this, you can either assign a section_body
property to each object in the array or adjust the interface to accommodate the possibility of the property being present or absent.
interface section {
id: string;
section_header: string;
section_body?: string;
sectionItems: any;
}
Your store should now be free of errors. For a more type-safe sectionItems
property, consider changing it from any
to Array<any>
, or deploying a more specific object type if you have foreknowledge of the appearance of the section items.