简体   繁体   中英

Type 'undefined[]' is not assignable to type 'number'

I started recently to learn typescript + Angular. I am having trouble understang the type assigment in variables. for example I have the following function:

    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;
}

and I want to use "pointLatLng" into the following block

 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'
    })
});

I thought I could do the following

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

But I got the errors :

Argument of type 'any[]' is not assignable to parameter of type 'LatLngExpression'. Type 'any[]' is not assignable to type '[number, number]'.

Property '0' is missing in type 'any[]'.

How can I change the type any[] into [number,number]

Did you mean:

let buslat: number[] = [];

( number[] rather than just a single number )

If you really only ever have two, use [number, number] , but then you cannot assign the empty array as default.

Explanation on the errors you had:

Consider this let buslat: number = [];

Here, you are defining a variable of type number . But you are assigning an array of type any to it. Therefore the error.

If you want a number array, you'd do like;

let buslat: number[] = [];

Similarly for the other array you have.

But, based on your comments and the example in question, here's what you probably want to do:

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];
}

Notes:

  • buslat and buslong are not arrays, they are just numbers. function

  • returns an array of numbers and defined that way using TS syntax

  • return statement returns an array of numbers, it does not need a variable to assign before it can return the array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM