Typescript 中的“通用类型‘Feature’需要 1 个类型参数”是什么意思?

2024-03-26

我尝试在打字稿中使用 GeoJson 但编译器会抛出这两个变量的错误:Generic type 'Feature<T>' requires 1 type argument(s)

  const pos = <GeoJSON.Feature>{
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [0, 1]
    }
  };

  const oldPos = <GeoJSON.Feature>{
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [2, 4]
    }
  };

这到底是什么意思呢?


Feature接口需要一个参数:

export interface Feature<T extends GeometryObject> extends GeoJsonObject
{
    geometry: T;
    properties: any;
    id?: string;
}

尝试这个:

  const pos = <GeoJSON.Feature<GeoJSON.GeometryObject>>{
    "type": "Feature",
    "properties":{},
    "geometry": {
      "type": "Point",
      "coordinates": [0, 1]
    }
  };

也许引入一个辅助类型并在 pos 上设置类型而不是强制转换将帮助您确保已设置所需的“properties”属性:

type GeoGeom = GeoJSON.Feature<GeoJSON.GeometryObject>;
const pos: GeoGeom = {
    type: "Feature",
    properties: "foo",
    geometry: {
        type: "Point",
        coordinates: [0, 1]
    }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Typescript 中的“通用类型‘Feature’需要 1 个类型参数”是什么意思? 的相关文章

随机推荐