Runtime Terror
Runtime Terror

Reputation: 6742

The meaning of <P = any> in TypeScript

I looked inside the leaflet.js definition file and there I found one strange thing: Marker<P = any>, where I can't figure out what P = any is for. I mean why is this not P: any?

The class implementation:

export class Marker<P = any> extends Layer {
    constructor(latlng: LatLngExpression, options?: MarkerOptions);
    toGeoJSON(): geojson.Feature<geojson.Point, P>;
    getLatLng(): LatLng;
    setLatLng(latlng: LatLngExpression): this;
    setZIndexOffset(offset: number): this;
    setIcon(icon: Icon | DivIcon): this;
    setOpacity(opacity: number): this;
    getElement(): HTMLElement | undefined;

    // Properties
    options: MarkerOptions;
    dragging?: Handler;
    feature?: geojson.Feature<geojson.Point, P>;
}

The full definition file: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/leaflet/index.d.ts

Upvotes: 2

Views: 2905

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249796

Marker is a generic type, with a type argument named P. Usually you have to specify the generic argument for a generic type. However if the definition of the generic type provides a default for the type argument (P = any) then the type can be used while omitting an explicit type argument:

let x: Marker // valid because there is a default of any for P will be the same as Marker<any>
let xy: Marker<number> // valid because Marker is generic

Upvotes: 4

Related Questions