Monday, September 4, 2017

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

Leave a Comment

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?

1 Answers

Answers 1

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.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment