A
A
aarifkhamdi2019-09-04 11:07:01
typescript
aarifkhamdi, 2019-09-04 11:07:01

How to add a new Request type to typing Express?

I want to add a new type Request. That is, there is a regular Request, but I want to make my own with a new field.
There is an easy way to do

declare module 'express-serve-static-core' {
    interface Request {
        auth?: {
            test: string
        }
    }
}

but then you have to check for undefined
I wrote like this, but I can’t figure out how to make friends with the routing with the type I added. Tell me please?:
declare module 'express-serve-static-core' {
    interface AuthorizedRequest<P extends Params = ParamsDictionary> extends Request<P> {
        auth: {
            test: string
        }
    }
}

spoiler
TSError: ⨯ Unable to compile TypeScript:
src/routers/user.ts:6:19 - error TS2769: No overload matches this call.
Overload 1 of 4, '(path: PathParams, ...handlers: RequestHandler>[]): Express', gave the following error.
Argument of type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to parameter of type 'RequestHandler>'.
Types of parameters 'req' and 'req' are incompatible.
Property 'auth' is missing in type 'Request>' but required in type 'AuthorizedRequest>'.
Overload 2 of 4, '(path: PathParams, ...handlers: RequestHandlerParams>[]): Express', gave the following error.
Argument of type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to parameter of type 'RequestHandlerParams>'.
Type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to type 'RequestHandler>'.
Overload 3 of 4, '(path: PathParams, subApplication: Application): Express', gave the following error.
Argument of type '(req: AuthorizedRequest>, res: Response) => Promise' is not assignable to parameter of type 'Application'.
Type '(req: AuthorizedRequest>, res: Response) => Promise' is missing the following properties from type 'Application': init, defaultConfiguration, engine, set, and 61 more.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question