簡體   English   中英

針對“ {}”的打字稿類型

[英]Typescript type against '{}'

我在與D3交互的Angular2中遇到大括號的類型錯誤:

.attr("cy", function (data) { return x([data.lon,data.lat])[1]; })

錯誤是:

error TS2339: Property 'lon' does not exist on type '{}'
error TS2339: Property 'lat' does not exist on type '{}'

attr行在函數內部,並且xlet x = this.projection;的別名let x = this.projection; this.projection返回一個功能。 data 一個對象。

通過調用傳遞了數據的方法來初始添加circles (此處沒有錯誤):

drawMarkers(map,stations,projection) {
        map.selectAll("circle")
        .data(stations)
        .enter()
        .append("circle")
        .attr("cx", function (d) { return projection([d.lon,d.lat])[0]; })
        .attr("cy", function (d) { return projection([d.lon,d.lat])[1]; })
        .attr("r", "1px")
        .attr("fill", "white")
        .attr('style','cursor: pointer;')
        .on('click',() => {
            this.flyoutservice.changeFlyoutState(true);
        });
    }

縮放后,將調用“縮放”功能,並將circles重新繪制到新位置(這是發生錯誤的位置):

map
        .selectAll('circle')
        .attr("cx", function (data) { return x([data.lon,data.lat])[0]; })
        .attr("cy", function (data) { return x([data.lon,data.lat])[1]; })
        .attr('r',(d) => {
            let cr = parseInt(d3.select(this).attr('r'), 10);

            let scale = d3.event.transform['k'];

            return 1 / d3.event.transform['k'];
        });

該錯誤在編譯時觸發,但運行時可以正常運行。

如果我這樣做: .attr("cx", function (data) { return x([data['object'].lon['number'],data['object'].lat['number'])[0]; })我的編譯錯誤消失了,但在運行時出現一個錯誤, lon無法讀取undefined屬性。 但是,盡管出現該錯誤,但一切運行正常。

您是否嘗試過在attr函數中定義data類型,以便Typescript將其識別為屬性?

.attr("cx", (data: { lon: number, lat: number }) => { return x([data.lon,data.lat])[0]; })
.attr("cy", (data: { lon: number, lat: number }) => { return x([data.lon,data.lat])[1]; })

為了保持一致,我還將以相同的方式更改第一個函數:

.attr("cx", (d: { lon: number, lat: number }) => { return projection([d.lon,d.lat])[0]; })
.attr("cy", (d: { lon: number, lat: number }) => { return projection([d.lon,d.lat])[1]; })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM