Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'd3 and 'd3-hexbin' in typescript as global libraries

So, I'm using d3 and d3-hexbin as global libraries:

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hexbin.v0.2.min.js"></script>

... and referencing them in .ts as:

/// <reference types="d3" />
/// <reference types="d3-hexbin" />

... using DefinitelyTyped definitions. However, although this works:

const svg = d3.select('#hitmap').append('svg')

... this:

const hexbin = d3.hexbin().radius(binsize + 1)

... fails with a :

Property 'hexbin' does not exist on type 
  'typeof "/Users/bytter/node_modules/@types/d3/index"'

Thoughts?

like image 878
Hugo Sereno Ferreira Avatar asked Aug 21 '17 21:08

Hugo Sereno Ferreira


1 Answers

Even though you have typings for d3, you don't have the derived typings for d3-hexbin. So you've to fall back to the declare method like I did here for d3-cloud: Typings for d3-cloud

Basically, the steps you've to follow are these:

  1. import the d3 library like usual, but give it an alias: import * as D3 from 'd3'; (Notice: Capital D for D3)

  2. declare d3 again so you can use it for hexbin: declare let d3: any;

  3. Use D3 for everything concerning the parent d3 library and d3 for hexbin generation alone.

const svg = D3.select('#hitmap').append('svg');

const hexbin = d3.hexbin().radius(binsize + 1);

This will prevent the editor from showing hexbin specific suggestions and Typescript will not be able to catch hexbin specific type errors. But unfortunately, till official typings arrive for hexbin, this is the best way I've found.

like image 171
Rajshri Mohan K S Avatar answered Oct 04 '22 08:10

Rajshri Mohan K S