简体   繁体   中英

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.

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM