Home > Blockchain >  How to declare a function parameter type as an express app?
How to declare a function parameter type as an express app?

Time:12-11

I have a node server which uses express, and I need to install metrics on it during setup. So I have something like:

const app = express();

installMetrics(app);

TypeScript is able to determine the type of app fine, as I've installed @types/express. But in declaring my function installMetrics, I don't know how to type the parameter app. If I try app: Express, I get an error: "Cannot use namespace 'Express' as a type". I could create a new type to mock the usage, but that's cumbersome, does not at all seem worth the effort/clutter.

As much as I hate to, it seems like my best option is to just use any. I've tried other solutions that I've found here such as declare type TExpress = typeof import("express") and it didn't get the correct type (because the import would need to be called to return the correct type). Am I missing something, or is this just a hole I'll have to patch over?

CodePudding user response:

If you hover over app you can see the inferred type which is Express. If you import it from express it will work:

import express, { Express } from  'express'

const app = express();

installMetrics(app);

function installMetrics(app: Express) {

}

Playground Link

CodePudding user response:

Since you have a reference to the function that returns the type you're interested in, you can have TypeScript extract its return value and use that to annotate as needed.

type App = ReturnType<typeof express>;

and

const installMetrics = (app: App) => {
  // ...
};
  • Related