Quantcast
Channel: When to use classes vs. interfaces in a TypeScript library? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

When to use classes vs. interfaces in a TypeScript library?

$
0
0

I have seen related questions like this one, but they all assume the difference between classes and interfaces are that classes can be instantiated while interfaces cannot. However, take for example @types/google.maps. For example:

declare namespace google.maps {  class Map extends google.maps.MVCObject {    constructor(mapDiv: HTMLElement, opts?: google.maps.MapOptions);    controls: google.maps.MVCArray<any>[];    data: google.maps.Data;    fitBounds(        bounds: google.maps.LatLngBounds|google.maps.LatLngBoundsLiteral,        padding?: number|google.maps.Padding): void;    // ...  }}declare namespace google.maps {  interface MapType {    alt: string|null;    getTile(        tileCoord: google.maps.Point|null, zoom: number,        ownerDocument: Document|null): Element|null;    maxZoom: number;    minZoom: number;    name: string|null;    projection: google.maps.Projection|null;    radius: number;    releaseTile(tile: Element|null): void;    tileSize: google.maps.Size|null;  }}declare namespace google.maps {  interface MapTypeControlOptions {    mapTypeIds?: (string)[]|null;    position?: google.maps.ControlPosition|null;    style?: google.maps.MapTypeControlStyle|null;  }}declare namespace google.maps {  class MapTypeRegistry extends google.maps.MVCObject {    set(id: string, mapType: any): void;  }}declare namespace google.maps {  interface MapsEventListener {    remove(): void;  }}declare namespace google.maps {  interface WebglCameraParams extends google.maps.CameraParams {    lat: number;    lng: number;  }}

Both interfaces and classes:

  • Extend other objects.
  • Have properties.
  • Have methods/functions.
  • Cannot be directly instantiated from these definitions.

Somewhere in the google maps code there is actually a class for both the classes defined here, and the interfaces defined here. It appears that the class definitions are for what a user can instantiate, vs. what the library can internally instantiate (interfaces).

So then, what are the deeper differences between interfaces and classes in these contexts? I get like what the other answer is saying, that classes usually are constructable, but these classes clearly are not directly instantiable. They represent other classes. But the interfaces represent other classes too. So I am confused.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images