Giovanni Azua Giovanni Azua - 4 years ago 159
TypeScript Question

How to call javascript libraries from Typescript project?

I'm working on an existing Typescript AngularJS project. Now I'd like to use d3js but to do so I need to manually download the d3js typescript (turns out d3 is made of a million files) and then the d3js min javascript. The corporate proxy doesn't allow me to use tools to download/manage dependencies etc so I only have the manual option.

Therefore I prefer to simply import the d3js in the

and invoke d3js directly from Typescript without using the d3 ts version.

So I do e.g.

var svg ="svg"),
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + + ")");

var x = d3.scaleBand()
.rangeRound([0, width])

but then I get the compiler errors "Cannot find name
" is there a way to tell in Typescript that this Javascript object is defined elsewhere and it should not assume anything about it?

It is a pity that d3 js is split in a million pieces ... I find that it is not very useful, who will ever use d3
? this makes no sense to me.

Answer Source

The definition file is only needed for compiling the ts source to js, it's not needed in order to run the js.

It will be the easiest to use it with @types:

npm install --save @types/d3

If you can't do that, then download the definition file manually and place it near your source and then reference it:

/// <reference path="PATH_TO_D3_D_TS" />

If you can't do that as well then declare it:

declare const d3: any;

That will tell the compiler that the variable d3 exists, and it's of type any, so you should not get exceptions from using it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download