Shumuu
Shumuu

Reputation: 172

Extend Express Middleware in Typescript

I am currently writing a REST API with Express and Typescript but I am having trouble extending the Request/Response of Express.

My IDE does not complain anymore, but Typescript throws TS2339 Errors when compiling with error TS2339: Property 'jsonStatusError' does not exist on type 'Response<any, Record<string, any>>'.

I have a jsonResponseMiddleware

import { NextFunction, Request, Response } from 'express';

export default (req: Request, res: Response, next: NextFunction) => {
  res.jsonStatusOk = (obj = {}) => res.json({ status: 'ok', data: obj });
  res.jsonStatusError = (obj = {}) => res.json({ status: 'error', data: obj });
  next();
};

and a main.d.ts

declare namespace Express {
  export interface Request {}
  export interface Response {
    // type definition for jsonResponseMiddleware
    jsonStatusOk: (obj: any) => void;
    jsonStatusError: (obj: any) => void;
  }
}

My tsconfig.json

{
  "compilerOptions": {
      "lib": ["es6"],
      "target": "es6",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true,
      "paths": {},
      "allowJs": true,
      "baseUrl": ".",
      "strict": false,
      "noEmitOnError": true,
  },
  "include": ["src/**/*"],
  "files": ["./src/types/main.d.ts"]
}

What am I missing ?

Upvotes: 2

Views: 1587

Answers (1)

pzaenger
pzaenger

Reputation: 11974

This attempt works for me.

Add a file named global.ts in your source folder:

declare global {
  namespace Express {
    export interface Response {
      jsonStatusOk: (obj: any) => void;
      jsonStatusError: (obj: any) => void;
    }
  }
}

Then in index.ts:

import './global';

[...]

Finally this should work:

import { Request, Response, NextFunction } from 'express';

export default (req: Request, res: Response, next: NextFunction) => {
  res.jsonStatusOk = (obj = {}) => res.json({ status: 'ok', data: obj });
  res.jsonStatusError = (obj = {}) => res.json({ status: 'error', data: obj });
  next();
};

I do not add anything to my tsconfig.json.

Upvotes: 3

Related Questions