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

如何在TypeScript中通过geojson模块及@types/geojson访问parse方法?

解决@types/geojson缺失parse方法类型的问题

方案1:扩展现有类型定义(推荐)

自己补全缺失的parse方法类型,既能保留类型检查,又不用忽略错误:

  • 在项目的类型目录下(比如src/types/)新建geojson.d.ts文件
  • 写入以下代码(可根据实际使用的参数调整类型):
declare module 'geojson' {
  export function parse<T>(
    data: T[],
    options: {
      Point?: (item: T) => [number, number];
      // 按需添加你用到的其他配置项类型,比如LineString、Polygon等
    }
  ): GeoJSON.FeatureCollection<GeoJSON.Point>;
}

TypeScript会自动识别这个扩展声明,之后调用parse就能获得正常的类型提示和检查。

方案2:用类型断言替代//@ts-ignore

如果不想写完整类型,用类型断言明确告知TS这里的方法签名,比直接忽略错误更清晰:

import * as GeoJSON from 'geojson';

// 手动指定parse方法的类型
const geojsonParse = GeoJSON.parse as unknown as (
  data: Record<string, any>[],
  options: { Point: (item: Record<string, any>) => [number, number] }
) => GeoJSON.FeatureCollection;

// 调用时用geojsonParse替代GeoJSON.parse
const features = geojsonParse(yourData, {
  Point: (item) => [item.lng, item.lat]
});

方案3:移除@types/geojson,使用模块自带类型

检查geojson模块本身是否包含类型定义(看它的package.json里有没有types字段),如果有的话:

  1. 卸载@types/geojson:
npm uninstall @types/geojson
  1. 确保tsconfig.json里的moduleResolution设置为node16或nodenext,让TS优先读取模块自带的类型文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:00:10