Search code examples
node.jstypescripttypescript-typingstyping

How to use external .d.ts for a module


I'm trying to understand what is the way to use an external, not provided by the module, .d.ts?

I'm trying to use xlsx which doesn't have type definitions and wrap it with the @types/xlsx.

I npm installed them both and figured I should add a reference to the typings/index.d.ts as follows: /// <reference path="../node_modules/@types/xlsx/index.d.ts" />

Now I find it hard to understand what do I need to import trying to use the xlsx with the type definition provided?

And maybe I simply got it all wrong and there's a simpler way.


Solution

  • Generally, nowadays you shouldn't ever need to manually add /// <reference... references. If you've got your type definitions installed using NPM then they should be automatically included in your compilation process.

    All you need to do is import the module and start using it. For example, in a new empty test project I've just installed xlsx (npm install xlsx @types/xlsx) and I can now successfully compile and run the below:

    import xlsx = require("xlsx");
    var workbook = xlsx.readFile("test.xlsx");
    

    That should be all you need.