Jarrad
Jarrad

Reputation: 1027

How can I just import typings into Typescript, without the whole module?

I am writing a piece of Express middleware in Typescript. It will be published to npm as a standalone package. I would like to be able to define my functions using Express types, as this lets me write with type safety:

function playWithRequest( req: express.Request, res: express.Response, next: express.NextFunction ) {
    req['key'] = 'stuff';
}

module.exports = playWithRequest;

However, I have no need to require('express') itself, and I want to avoid import statements that will generate such a require() call. How can I tell Typescript about the express types without importing express itself?

The express typings are installed by npm install @types/express, and are thus hanging around in node_modules/@types/express/index.d.ts.

Upvotes: 5

Views: 2695

Answers (1)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

By default TypeScript will not transpile an import to require statement, which has no JS-only exports used in the compiled file.

So no require call will be generated when you only use the types exported by @types/express.

When you make such module ( that needs express only for typings ) you can safely put @types/express into your dependencies ( not devDependencies ) and keep express module inside your devDependencies ( for compilation purposes ).

By doing this whenever you install your module to your application it will be properly safe-typed but it won't complain that express is not there.

Upvotes: 9

Related Questions