Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to declare variable of type Express in TypeScript without importing express?

I have main file called main.ts where I imported express with

import express from 'express';

Then I have another class in separate file where I want to create method "init" which has one parameter named "app" of type Express. But somehow i can’t say app:Express without importing express.

My goal is to import express only once and keep it in a main.ts file, and then in a main.ts file I will call "init" method ( from a separate file) where I will pass that imported express.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Main.ts file

import express from 'express';


import { FriendsRouter } from './routes/friends.router';

const app = express();

FriendsRouter.init(app);

const PORT:number = 3000;

app.listen(PORT,()=>{
    console.log('Listening at '+PORT);
})

Spearete file (friends router in my case)

export class FriendsRouter {

private constructor(){
     
}


public static init(app:Express): void{
  
    app.get('/friends',someMethod);

}

}

Problem is, in FriendsRouter file, I can’t say app: Express.
How can I fix this ?

>Solution :

The usual thing is to import the type Express from the express package:

import { Express } from "express";

Note that that’s just importing the type, not the function. The rest of your code is then fine as-is (including the type on app).

If you don’t have that type, install the types for express like this:

npm install --save-dev @types/express

…but you’ve probably already done that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading