React TypeScript报错“类型不可分配给never类型” 多post类型遍历问题
报错根因
你当前的代码存在4个核心问题导致类型报错:
- 你写的
useSelect回调没有返回任何值,导致pages变量为undefined,调用pages.map自然报错 - 初始化
postList = []未声明类型,TS默认推断为never[],后续推入非never类型的数据就会触发类型不匹配错误 getEntityRecords查询可能返回null,你没有做非空判断就直接操作,会引入无效值- 直接把每类文章的数组
push到postList,会得到二维数组,后续map时没法直接读取单篇文章的id、title属性
修正后完整代码
const pages = useSelect((select) => { const editor = select("core/editor"); const currentPostType: string = editor.getCurrentPostType(); // 这里可以替换为你需要的任意文章类型数组,比如 ['page', 'post', 'product'] const selectablePostTypes = [currentPostType, "products"]; // 显式声明数组类型,避免TS推断为never[] const postList: { description: string; id: number; featuredMedia: number; link: string; subtitle: string; title: string; }[] = []; selectablePostTypes.forEach((singlePostType) => { const records: Record<string, any>[] | null = select("core").getEntityRecords( "postType", singlePostType ); // 非空判断 + 结构统一处理 + 扁平推入数组,避免生成二维数组 if (records) { const formattedRecords = records.map(record => ({ description: record.description, id: record.id, featuredMedia: record.featuredMedia, link: record.link, subtitle: record.subtitle, title: record.title.rendered, })) postList.push(...formattedRecords); } }); // 必须返回处理好的数组给pages变量 return postList; }); // 生成下拉选项pagesOptions const pagesOptions = [ { value: "0", label: __("No page selected", "demosite"), }, ...pages.map((page) => ({ value: page.id, label: page.title, })), ];
关键修改说明
- 给
postList显式声明了结构类型,避免TS自动推断为never[] - 对
getEntityRecords的返回值做了非空判断,避免空值报错 - 拿到每类文章的查询结果后先做结构格式化,和你之前单类型的处理逻辑保持一致,保证
title是字符串而非对象 - 用扩展运算符
...formattedRecords把单篇文章逐个推入postList,得到的是一维文章数组,后续可以直接map遍历 - 给
useSelect补充了返回值,pages变量就能拿到正确的文章数组
内容的提问来源于stack exchange,提问作者Gurdt
相关产品推荐
相关产品推荐

