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

TypeScript定义Google返回JSON对象数组接口时索引报错解决

报错根因
  • 类型层面:for...in循环取出的key默认类型是通用string,但你定义的Geocode是固定属性结构(仅包含data、error两个明确字段),没有定义「接收任意string类型键、返回对应值」的索引签名,TypeScript不允许用不确定的字符串键访问固定结构类型的属性,因此抛出类型错误。
  • 逻辑层面:遍历逻辑本身存在运行时风险:Geocode结构里只有data字段可能存在address_components属性,error字段是字符串/Null,完全没有这个属性,遍历所有键会在访问error属性时触发Cannot read properties of null (reading 'address_components')这类运行时错误。
修复后实现

不需要遍历Geocode的外层键,直接做空值判断后读取目标字段即可,可直接复用@types/google.maps自带的类型定义,不需要手动声明地址项结构:

type Geocode = {
  data?: google.maps.GeocoderResult | null;
  error: string | null;
};

export interface CityState {
  city?: string;
  state?: string;
}

export const parseForCityAndState = (data: Geocode): CityState => {
  const cityState: CityState = {
    city: '',
    state: '',
  };

  // 仅当存在有效地址组件数据时执行遍历
  if (data.data?.address_components) {
    data.data.address_components.forEach((ele) => {
      // 优先匹配sublocality,其次匹配locality作为城市值
      if (ele.types.includes('sublocality') || ele.types.includes('locality')) {
        cityState.city = ele.short_name;
      }
      // 匹配一级行政区作为州/省值
      if (ele.types.includes('administrative_area_level_1')) {
        cityState.state = ele.short_name;
      }
    });
  }

  return cityState;
};
可选扩展(非当前场景必需)

如果你确实有通用场景需要用字符串键访问Geocode类型属性,可以给类型添加索引签名,但当前业务场景下不推荐这么做,会掩盖不必要的逻辑错误:

// 索引签名写法参考
type Geocode = {
  [key: string]: google.maps.GeocoderResult | string | null | undefined;
  data?: google.maps.GeocoderResult | null;
  error: string | null;
};

内容的提问来源于stack exchange,提问作者Vash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 03:48:43