TypeScript: Extending Request
The above example uses a custom AuthenticatedRequest
instead of regular Request
as the type of the req
object. This is because in TypeScript, if we try to add a new parameter, in this case "user", to a Request
object, we get an error
Property 'user' does not exist on type
'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'
We are trying to set a value to request property "user", but request objects are well defined objects that have no such property.
We can not add or use properties that an object does not have. This is part of the type safety that TypeScript is here to enforce. If an object is of type Request, we know exactly what the properties are.