Type 'string[]' cannot be used as an index type报错及取值undefined问题
问题原因
- 编译类型错误:
GetStaticProps默认的context.params类型为ParsedUrlQuery,其字段值的类型是string | string[] | undefined,TS无法确定organizationId一定是字符串类型,因此抛出“数组不能作为索引类型”的错误。 - 运行时取值为undefined:JS对象的键是大小写敏感的,你接口返回的
organizationList2的键为大写格式的UUID,而路由参数拿到的organizationId是全小写格式,大小写不匹配导致无法命中对应键值。
解决方法
- 首先给
GetStaticProps指定泛型,明确路由参数的类型,消除类型报错:
// 定义当前页面的路由参数类型 interface PageParams { lang: string; organizationId: string; } // 给GetStaticProps传入泛型,第一个为页面props类型,第二个为params类型 export const getStaticProps: GetStaticProps<{}, PageParams> = async (context) => {
- 统一大小写后再进行索引取值,修正取值逻辑:将路由拿到的
organizationId转为大写(或提前把organizationList2的所有键转为小写,只要两端格式统一即可),再去获取对应对象。 - 调整变量定义顺序,先处理参数再取值,避免重复定义变量。
修正后的完整代码:
interface PageParams { lang: string; organizationId: string; } export const getStaticProps: GetStaticProps<{}, PageParams> = async (context) => { const organizationList2Data = await fetch(`${baseURL}getSMOrganizations`, { method: "post", headers: { "Content-Type": "application/json" }, }); const organizationList2 = await organizationList2Data.json(); // 统一转换为大写匹配接口返回的键格式 const organizationId = context.params.organizationId.toUpperCase(); const organization = organizationList2[organizationId]; return { props: { organizationId, organization: organization ?? "", }, revalidate: 600, }; };
内容的提问来源于stack exchange,提问作者János
相关产品推荐
相关产品推荐

