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

Time:07-01

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.

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 ?

CodePudding user response:

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.

  • Related