frank
frank

Reputation: 1302

How to Write Typescript d.ts FIle to Extend @types/d3

I'm search on google and successfully extend d3js selection with the following ts code:

import * as d3 from "d3";
d3.selection.prototype.popover = function() {};

And then use it from another ts file like:

(d3.select("svg").selectAll(".node") as any).popover();

This works, but I dno't like "any" here and want to extend the @types/d3 definition (I alread install @types/d3). I create a d3.extend.d.ts along the function code ts file, and write:

/// <referencepath="../../node_modules/@types/d3-selection/index.d.ts">
declare module "d3-selection"{
   export interface Selection<GElement extends BaseType, Datum, PElement extends BaseType, PDatum>{
      popover();
   }
}

But this seems doesn't work, if I remove any from the calling code, ts compiler will get error.

Updated: I updated my code based on the answer to make it to be the final work version

Upvotes: 2

Views: 1013

Answers (1)

cartant
cartant

Reputation: 58400

Your declaration merging needs to use the name of the module - d3-selection - in which Selection is declared. Like this:

declare module "d3-selection" {
  export interface Selection<
    GElement extends BaseType,
    Datum,
    PElement extends BaseType,
    PDatum
  > {
    popover(): void;
  }
}

Upvotes: 1

Related Questions