You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Type 'string[]' cannot be used as an index type报错及取值undefined问题

问题原因
  • 编译类型错误:GetStaticProps默认的context.params类型为ParsedUrlQuery,其字段值的类型是string | string[] | undefined,TS无法确定organizationId一定是字符串类型,因此抛出“数组不能作为索引类型”的错误。
  • 运行时取值为undefined:JS对象的键是大小写敏感的,你接口返回的organizationList2的键为大写格式的UUID,而路由参数拿到的organizationId是全小写格式,大小写不匹配导致无法命中对应键值。
解决方法
  1. 首先给GetStaticProps指定泛型,明确路由参数的类型,消除类型报错:
// 定义当前页面的路由参数类型
interface PageParams {
  lang: string;
  organizationId: string;
}
// 给GetStaticProps传入泛型,第一个为页面props类型,第二个为params类型
export const getStaticProps: GetStaticProps<{}, PageParams> = async (context) => {
  1. 统一大小写后再进行索引取值,修正取值逻辑:将路由拿到的organizationId转为大写(或提前把organizationList2的所有键转为小写,只要两端格式统一即可),再去获取对应对象。
  2. 调整变量定义顺序,先处理参数再取值,避免重复定义变量。

修正后的完整代码:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:15:00