EternallyCurious
EternallyCurious

Reputation: 2415

Trying to create Typescript definition for NodeJS module

I am trying to create a Typescript definition for the NodeJS formidable module that I want to use to upload files to the server. But that throws an error. The typescript compiler does not compile the statement "import formidable = require('formidable');" to its javascript equivalent. I need to know if the formidable definition is correct.

Here's the upload.ts which contains the file parse code:

import fs = require('fs');
import path = require('path');
import formidable = require('formidable');
var formidable = new formidable.Formidable(); 

Here's the upload.js which is created by the typescript compiler:

var fs = require('fs');
var path = require('path');

var formidable = new formidable.Formidable();

The typescript compiler is not creating a require statement for the formidable module. this needs to be fixed.

Here's the typescript definition file:

/// <reference path="../Main.d.ts" />

declare module "formidable" {
    export interface Formidable {
        IncomingForm(): Formidable;
    }
}

Upvotes: 1

Views: 666

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220944

Here's what's going on:

Because your Formidable module doesn't contain any values (vars, classes, or modules containing vars or classes), it doesn't create a name in the "value space" (Typescript has three different namespaces - types, values, and namespaces).

When you import something, you get "all meanings" of the imported value. In this case, because there is no value in the Formidable module, the import does not create any object called formidable in the value space.

Then you do this:

import formidable = require('formidable');
var formidable = new formidable.Formidable();

When resolving the expression new formidable.Formidable(), the compiler looks for a value called formidable. It finds one - the var you just created (don't have vars with the same name as imports - this wouldn't work in JavaScript code either...). Because the variable is used in its own initializer, type inference just resorts to any.

Essentially what you've done is this:

var x = new x.y(); // ??

Going back to the root problem, your definition file for Formidable needs to include some value. It should probably look like this (with a class instead of an interface):

declare module "formidable" {
    export class Formidable {
        IncomingForm(): Formidable;
    }
}

Upvotes: 4

Related Questions