我不明白为什么会出现此错误:
Argument of type '{ id: string; }' is not assignable to parameter of type 'never'.
... 在行 const index = state.sections.findIndex((section) => section.id === id);
在我的 Vue 商店的以下部分:
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);
},
};
最佳答案
当您不为值提供类型时(在本例中为函数的返回值),TypeScript 会尝试将其缩小到最准确的类型。由于您返回的对象的 sections
' 项目数组总是空的,它将它们推断为 never[]
( type[]
是 Array<type>
的别名);一个实际上不能包含任何值的数组。您可以在以下代码段中看到这一点:
const functionReturningEmptyArray = () => ({ items: [] });
type EmptyArray = ReturnType<typeof functionReturningEmptyArray>;
// type EmptyArray = { items: never[] }
解决此问题的一种方法是使用 section
您创建的接口(interface),用于指定 state
的返回类型.
export const state = (): { sections: Array<section> } => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
第一行空括号后的冒号指定函数的返回类型。在这种情况下,我已经内联了对象类型,因为它只有一个属性,但是如果您的 state
更复杂,或者如果你只是喜欢可读性,你可以将它提取到一个单独的类型并将其作为返回类型引用;
interface MyState {
sections: Array<section>;
}
export const state = (): MyState => ({
sections: [
{
id: '1',
section_header: 'lorem',
sectionItems: []
},
{
id: '2',
section_header: 'ipsum',
sectionItems: []
}
]
});
此时,TypeScript 将对您的返回值抛出错误,因为您的 section
接口(interface)指定该对象还应具有 section_body
属性,您返回的 sections
中缺少该属性大批。要解决此问题,您可以给数组中的每个对象一个 section_body
属性,或修改接口(interface)以匹配属性可能存在或可能不存在的事实;
interface section {
id: string;
section_header: string;
section_body?: string;
sectionItems: any;
}
您的商店现在应该没有错误,但要有一个更安全的类型 sectionItems
属性,您也可以将其更改为 any
至 Array<any>
,或者如果您事先知道部分项目的外观,则使用更具体的对象类型。
关于arrays - "Not assignable to parameter of type never"Vue存储数组声明TS错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70475907/