3

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Kesem David
  • 2,135
  • 3
  • 27
  • 46
  • import xlsx = require("../node_modules/@types/xlsx/index"); – RKS_Code Nov 30 '16 at 00:04
  • @Ramakant I figured the import = require is done for modules with no dts, you say I should do that on the dts itself? How would this imported star be connected to the js source code of the xlsx? – Kesem David Nov 30 '16 at 06:20

1 Answers1

1

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.

Kesem David
  • 2,135
  • 3
  • 27
  • 46
Tim Perry
  • 11,766
  • 1
  • 57
  • 85
  • Thanks for your answer Tim, maybe i understood it wrong when i first encountered the `import XX = require('XXX')` but doesnt it go for the modules I want to import when i DONT have a d.ts? the `xlsx` wont be typed right? how could i achieve the behavior of `import {IWorkBook} from 'xlsx'` with an external d.ts? i want to be able to define `let workbook: IWorkBook = xlsx.readFile('test.xlsx');` – Kesem David Nov 30 '16 at 14:14
  • No, it's actually the correct syntax for non-ES6 module imports, and is preferred in cases like this. See http://stackoverflow.com/a/29598404/68051. You might be thinking of `var XX = require('XXX')`, which doesn't get types included. With the above example `xlsx` is actually correctly typed here; if you try to add a middle line with `xlsx.abc()` it won't compile, because it knows that's an invalid method. – Tim Perry Nov 30 '16 at 14:32
  • If you want to use the new syntax, you can write `import * as xlsx from "xlsx"` and then use `xlsx.IWorkBook` or `xlsx.readFile`, or you can import them individually if you'd prefer with `import { readFile, IWorkBook } from "xlsx"`. Generally for non-ES6 modules I just always use the old syntax (`import X = ...`) though, because the new syntax is technically invalid if they've used `module.exports = ...`. – Tim Perry Nov 30 '16 at 14:35
  • Thanks a lot for the answer :) – Kesem David Dec 02 '16 at 15:51