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

TypeScript报错:类型'string'不存在属性'data'.ts(2339)求助

解决TypeScript错误:Property 'data' does not exist in type 'string'

错误原因

你遇到的ts(2339)错误,核心问题是TypeScript判定fetchLocalMapBox(inputValue)的返回值为string类型,但代码里却试图访问它的data属性——字符串本身不存在该属性,因此触发报错。

解决方案

1. 检查fetchLocalMapBox的返回值结构

如果这是你自行封装的函数,先确认它是否返回了预期的结构化数据:

  • 若函数内部使用原生fetch,可能遗漏了JSON解析步骤,导致返回原始文本(string类型):
    // 错误写法:直接返回响应文本
    async function fetchLocalMapBox(input: string) {
      const res = await fetch(`your-api-url?input=${input}`);
      return res.text(); // 返回string
    }
    
    // 正确写法:解析为JSON对象
    async function fetchLocalMapBox(input: string) {
      const res = await fetch(`your-api-url?input=${input}`);
      return res.json(); // 返回包含data字段的JSON对象
    }
    

2. 为fetchLocalMapBox添加明确类型定义

给函数指定返回类型,让TypeScript明确其返回结构:

// 定义响应数据的类型结构
interface MapBoxResponse {
  data: {
    features: Array<{
      place_name: string;
      center: [number, number];
    }>;
  };
}

// 给函数标注返回类型
async function fetchLocalMapBox(input: string): Promise<MapBoxResponse> {
  const res = await fetch(`your-api-url?input=${input}`);
  return res.json();
}

3. 临时修复:类型断言(仅应急使用)

如果fetchLocalMapBox是第三方库函数且类型定义缺失,可临时用类型断言绕过错误(不推荐长期使用,建议补全官方类型):

const response = await fetchLocalMapBox(inputValue) as unknown as MapBoxResponse;

修正后的完整代码示例

// 定义业务所需类型
interface Place {
  label: string;
  value: string;
  position: {
    lat: number;
    lng: number;
  };
  place: string;
}

interface MapBoxFeature {
  place_name: string;
  center: [number, number];
}

interface MapBoxResponse {
  data: {
    features: MapBoxFeature[];
  };
}

// 修正后的请求函数
async function fetchLocalMapBox(input: string): Promise<MapBoxResponse> {
  const res = await fetch(`your-api-endpoint?input=${input}`);
  if (!res.ok) throw new Error('地址搜索请求失败');
  return res.json();
}

const loadOptions = async (inputValue: string, callback: (places: Place[]) => void) => {        
  const response = await fetchLocalMapBox(inputValue);

  const places = response.data.features.map((item) => ({
    label: item.place_name,
    value: item.place_name,
    position: {
      lat: item.center[1],
      lng: item.center[0]
    },
    place: item.place_name,
  }));

  callback(places);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:12:16