Reputation: 23
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]
Upvotes: 2
Views: 2878
Reputation: 5289
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
Upvotes: 0
Reputation: 184376
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.
Upvotes: 1