Abazhenov / express-async-handler

Async Error Handling Middleware for Express
572 stars 39 forks source link

Typescript error while augmenting express.Request #53

Open AlonMiz opened 2 years ago

AlonMiz commented 2 years ago

having type mismatch when adding a field to express.Request object (augmenting - see express.d.ts below). without using async handler, everything works great. it seems that it confusing with express/express-serve-static-core types for some reason

working with these versions

    "@types/express": "4.17.13",
    "express": "4.17.3",
    "express-async-handler": "^1.1.4",

import asyncHandler from 'express-async-handler';

export const createController = asyncHandler(
  async (request: Request<unknown, unknown, Partial<ISmokestack>>, response: Response) => {
    const { account } = await accountService.getCurrentUserAccount(request.context?.uid);
    if (!account) return response.status(404).send('no account found');

    const smokestack = new Smokestack(request.body);
    smokestack.factoryId = account.id;

    await smokestack.save();

    return response.send(smokestack);
  }
);

the augmentation under express.d.ts

import { auth } from 'firebase-admin';

declare module 'express' {
  export interface Request {
    context: auth.DecodedIdToken;
  }
}

the full error

Argument of type '(request: Request<unknown, unknown, Partial<ISmokestack>>, response: Response) => Promise<Response<any, Record<string, any>>>' is not assignable to parameter of type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
  Types of parameters 'request' and 'req' are incompatible.
    Property 'context' is missing in type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' but required in type 'Request<unknown, unknown, Partial<ISmokestack>, ParsedQs, Record<string, any>>'.ts(2345)
express.d.ts(5, 5): 'context' is declared here.
image
waddington commented 2 years ago

I'm also facing this issue using middleware that attaches a User object to the request.