Reputation: 1
I have a typescript interface:
export interface LatLng {
constructor(lat: number, lng: number): void;
lat(): number;
lng(): number;
}
And array with a type of LatLng:
path: Array<LatLng>;
How can i push elements to this array ?
Upvotes: 0
Views: 235
Reputation: 5598
Implement interface
export class LatLngNew implements LatLng {
constructor(public lat: number, public lng: number) {}
}
You can write like this
this.path.push(new LatLngNew(2,3))
Also you can define array type like this
path: LatLng[];
Upvotes: 2
Reputation: 164177
If you only have an interface then you should not have the constructor
there and it should look like this:
export interface LatLng {
lat(): number;
lng(): number;
}
You can then push a new item like so:
path.push({
lat: function() { return 0; },
lng: function() { return 0; },
});
You can also create a factory function for it:
function createLatLng(lat: number, lng: number): LatLng {
return {
lat: function() { return lat; },
lng: function() { return lng; }
};
}
If you want a class then you do it like so:
class LatLng {
constructor(private _lat: number, private _lng: number) {}
lat() {
return this._lat;
}
lng() {
return this._lng;
}
}
And push a new instance like so:
path.push(new LatLng(0, 0));
Upvotes: 1