DEV Community

George C. Norris
George C. Norris

Posted on

How to extend and use an extended Request type in Typescript / Express?

How to extend and use an extended Request type in Typescript / Express?

I'm adding a BUNCH of middleware libraries that extend the Request Object. I.E. One added user to req. Another add cookie() to req. Another add csrfToken() to req. etc..

When I add a request handler function, how do I tell that function to use the req with all the bells and whistles added by middleware?

Do I hunt down every DefinitelyTyped package corresponding to the middleware? If so, then will the Request type be magically 'decorated` with these properties?

To make it even harder, I've written my own middleware that adds properties to Request

req.myCustomFunction()

In this case, will I need to declare, and extend the Request myself with myCustomFunction?

In addition, will that Request which I am extending 'include' the types given by DefinitelyTyped?


declare namespace Express {
export interface Request {
myCustomFunction: () => void
}
}

Will this now include ALL the properties included via DefinitelyTyped AND my myCustomFunction?

How do I reference this interface when using?

Will it be Express.Request? Or just Request?

If I reference it as Request, how does Typescript know to use "my" Request and not the one exported by Express's DefinitelyTyped library?

`
declare namespace Express {
export interface Request {
import_destination?: string;
isZipImport?: boolean;
method: string;
originalname: string;
unzippedPath?: string;
url: string;
user?: TUser;
}

`

DOES NOT WORK


declare module global {
interface Request {
file?: FileObj;
files?: FileObj[];
user?: TUser;
isZipImport?: boolean;
unzippedPath?: string;
}
}
`
DOES NOT WORK

`
declare global {
declare module 'express' {
export interface Request {
file?: FileObj;
files?: FileObj[];
user?: TUser;
isZipImport?: boolean;
unzippedPath?: string;
}
}
}
`

DOES NOT WORK

`
declare namespace Express {
export interface Request {
user?: TUser;
isZipImport?: boolean;
unzippedPath?: string;
}
}

`




DOES NOT WORK


I'm seriously pulling my hair out trying to get this work. 
WHY WHY WHY.. is this so complicated to make work????

Top comments (0)