I don't understand why I'm getting this error:
Argument of type '{ id: string; }' is not assignable to parameter of type 'never'.
... at the line const index = state.sections.findIndex((section) => section.id === id);
in the following portion of my Vue store:
import { MutationTree, ActionTree, GetterTree } from 'vuex';
interface section {
id: string;
section_header: string;
section_body: string;
sectionItems: any;
}
interface sections extends Array<section>{}
export const state = () => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
type EditorState = ReturnType<typeof state>;
export const mutations: MutationTree<EditorState> = {
ADD_SECTION_ITEM(state, id) {
const index = state.sections.findIndex((section) => section.id === id);
const sectionItem = {
id: randomId()
}
state.sections[index].sectionItems.push(sectionItem);
},
};
CodePudding user response:
I would say you probably need to type your sectionItems:
interface SectionItem {
id: string
}
interface Section {
id: string;
section_header: string;
section_body?: string;
sectionItems: SectionItem;
}
Because, when you don't specify the type of sectionItems, typescript looks at the sectionItems that you initialised in your state (which are equal to []) and cannot identify the type of elements that should be in this array.
So you define it. Also, section_body should be optional because you it's not there in all your examples. Interface names should be capitalised in typescript.
Also, I do not think you need the sections interface. if you want to type something as an array of an interface, just use section[] as the type, like you would do string[].
Finally, this is up to you but I would advise against using different naming conventions in your interfaces (and in your code in general): section_body is snake_case and sectionItems is camelCase, it's usually better to stick to one and keep it in all the code.
CodePudding user response:
I think you need state.sections.push(sectionItem)
instead of state.sections[index].sectionItems.push(sectionItems)
.