0

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 ?

2
  • Do you actually have a class like that? Where is the implementation of this constructor? Commented Sep 19, 2017 at 13:31
  • No implementation. How can I implement this interface in class ? Commented Sep 19, 2017 at 13:58

2 Answers 2

2

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[];
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

I did't create this interface. angular-maps.com/api-docs/agm-core/interfaces/…. But I need to use this interface as a type and give elements.
Oh, it's an existing library, ok then the implementation probably already exists and you are only talking about the types. The other answer by @alexKhymenko should work for you then
Answer by @alexKhymenko doesn't work. It shows error: '''LatLng' only refers to a type, but is being used as a value here."
You'll need to edit your question and add more of your code, how you use this type and so on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.