franza
franza

Reputation: 2317

TypeScript - type annotation for NodeJS module

In the NodeJS project I'm working on right now we use dependency injection, and along with instances of custom-written classes we used to pass modules like fs, crypto, http and others as an argument into constructor.

Now we would like to use TypeScript with DefinitelyTyped library to support NodeJS types. In case of NodeJS modules, it is not clear for me how can I describe the type definition for modules in TypeScript?

Example:

class ReportWriter {
    private fs: ???;
    constructor (fs: ???) { //what should I use instead of ???
        this.fs = fs;
    }
}

I can create a type alias like (or maybe an interface):

type NodeFsModule = { 
    readFile: Function, 
    readFileSync: Function 
};

But it requires me to describe a huge amount of functions. Is there any alternative?

Upvotes: 1

Views: 1532

Answers (1)

basarat
basarat

Reputation: 275987

Just use import with typeof:

import fs = require('fs');
class ReportWriter {
    private fs: typeof fs;
    constructor (fs: typeof fs) {
        this.fs = fs;
    }
}

More here : https://basarat.gitbooks.io/typescript/content/docs/project/declarationspaces.html

Upvotes: 4

Related Questions