类型'Feature <point,{=“” [name:=“”字符串]:=“”任何; =“”} =“”>'类型不存在属性'features'

时间:2019-05-07 12:03:26

标签: angular d3.js geojson topojson

我是Angular的新手,我正在尝试使用Angular / d3构建德国地图。地图数据存储在Topojson文件plz_map_ger.json中:

{
"type": "Topology",
"arcs": [...],
"transform": {...},
"objects": {
      "plz5stellig": {...}
      }
 }

这是我绘制地图的代码:

import * as d3 from "d3";
import * as t from 'topojson';

...

d3.json("../../assets/plz_map_ger.json")
  .then(function(top:any) {
    g.selectAll('path')
      .data(t.feature(top, top.objects.plz5stellig).features)
      .enter()
      .append('path')
      .attr('d', path)
      .attr("class","kreisgrenzen")
      .on("click", function() {
        d3.select(this).attr("class","selected-kreis");
      });

但是我收到以下编译错误:

error TS2339: Property 'features' does not exist on type 'Feature<Point, { [name: string]: any; }>'.

该如何解决?

编辑: 当我将鼠标悬停在VS Code中的错误上时,我收到以下消息:

Property 'features' does not exist on type 'Feature<Point, { [name: string]: any; }>'.ts(2339)

我使用以下由mapshaper.org创建的Topojson文件(此文件有点简化,但是结构保持不变): gist.github.com/.../plz_map_ger.json

1 个答案:

答案 0 :(得分:1)

根据the types,函数feature()返回FeatureFeatureCollection。您需要的只有FeatureCollection具有.features属性。

检查code of the TopoJSON Package(第4-8行),我们可以看到,仅返回FeatureCollection的{​​{1}}  将topology作为其GeometryCollection

type

您正在异步加载export default function(topology, o) { return o.type === "GeometryCollection" ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature(topology, o); })} : feature(topology, o); } ,因此编译器无法知道其topology是否为.type

为了解决此问题,您将需要安装GeoJSON类型(GeometryCollection)。

然后您可以设置临时变量的类型

npm i @types/geojson

或者您可以将集合显式转换为功能集合(由于@altocumulus)

    ...
    d3.json("../../assets/plz_map_ger.json")
      .then(function(top:any) {

          // This row sets the temporary variable
          let mapFeatures: FeatureCollection = t.feature(top, top.objects.plz5stellig)

           g.selectAll('path')

          // We use the temporary variable here
          .data(mapFeatures.features)
          .enter()
          .append('path')
          .attr('d', path)
          .attr("class","kreisgrenzen")
          .on("click", function() {
            d3.select(this).attr("class","selected-kreis");
          });
      });