类型“ undefined []”不可分配给类型“数字”

时间:2018-12-17 16:50:14

标签: angular typescript

我最近开始学习打字稿+ Angular。我无法理解变量中的类型分配。例如,我具有以下功能:

    requestBusPoints() {
    //let busName = this.name;
    let buslat: number = [];  

    let buslong: number = [];

    for (let i = 0; i < this.customerSources.length; i++) {

       //busName[i] = this.customerSources[i]._source.name;
        buslat[i] = this.customerSources[i]._source.lat;
        buslong[i] = this.customerSources[i]._source.long;
    }
    var pointLatLng = [buslat, buslong];

    return pointLatLng;
}

我想在以下代码块中使用“ pointLatLng”

 summit = marker(latlng:[ 46.8523, -121.7603 ], options:{
    icon: icon({
        iconSize: [ 25, 41 ],
        iconAnchor: [ 13, 41 ],
        iconUrl: 'leaflet/marker-icon.png',
        shadowUrl: 'leaflet/marker-shadow.png'
    })
});

我认为我可以做到以下

summit = marker(this.requestBusPoints(),...

但是我得到了错误:

'any []'类型的参数不能分配给'LatLngExpression'类型的参数。 类型'any []'不可分配为类型'[数字,数字]'。

缺少属性'0'的类型为'any []'。

如何将any []类型更改为[number,number]

2 个答案:

答案 0 :(得分:0)

您的意思是:

let buslat: number[] = [];

({number[]而不是单个number

如果实际上只有两个,请使用[number, number],但是您不能将空数组指定为默认数组。

答案 1 :(得分:0)

您所犯错误的说明:

考虑此let buslat: number = [];

在这里,您正在定义类型number的变量。但是您要为其分配一个类型为any的数组。因此出现错误。

如果您想要一个数字数组,您会想要的;

let buslat: number[] = [];

与您拥有的其他阵列类似。

但是,根据您的评论和所涉及的示例,这可能是您想要做的:

requestBusPoints(): number[] {
    //let busName = this.name;
    let buslat: number;  
    let buslong: number;

    for (let i = 0; i < this.customerSources.length; i++) {

       //busName[i] = this.customerSources[i]._source.name;
        buslat = this.customerSources[i]._source.lat;
        buslong = this.customerSources[i]._source.long;
    }
    return [buslat, buslong];
}

注意:

  • buslat和buslong不是数组,它们只是数字。功能

  • 返回一个数字数组,并使用TS语法以这种方式定义

  • return语句返回一个数字数组,它不需要 在返回数组之前要分配的变量

相关问题