Express has been my go to server side node web framework for the past few years. Its fast, unopinionated and so easy to get up and running. I really love using it along with Typescript too, I should say. It enhances code quality and understand-ability. Refactoring your code in Typescript is also much more easier and faster. Plus, you get the added advantage of code completion and IntelliSense when using modern text editors like Visual Studio Code. 😋
One of the concepts of Typescript which I've recently began using is Declaration Merging
.
Declaration Merging allows you to merge two or more distinct declaration or types declared with the same name into a single definition. This concept allows you to attach your own custom property onto another Typescript interface type. Lets take a look at a typical Express middleware.
The above code is an Express middleware that is used to ensure that a user is authenticated when he or she tries to access a protected resource. It decodes the user's token from the authorization property of the request headers and attaches the user to the Request object. But see that red squiggly line?
Thats because the property currentUser
does not exist on Express's Request interface type. Let's fix that. 😃
The first thing we need to do is to create a new declaration file @types > express > index.d.ts
in the root of our project.
You would notice this is the exact same file name and path in our node_modules/@types
folder. For Typescript declaration merging to work, the file name and its path must match the original declaration file and path.
Next we need to make some few changes in the project's tsconfig.json
file. Let's update the typeRoots
value to the following:
...
"typeRoots": [
"@types",
"./node_modules/@types",
]
...
By default, the Typescript compiler looks for type definitions in the node_modules/@types
folder. The above code instructs the compiler to look for type definitions in this folder as well as our custom @types
folder in our project root.
It's now time to add our custom currentUser
property to Express's Request interface type by modifying the index.d.ts
file we created earlier:
import { UserModel } from "../../src/user/user.model";
declare global{
namespace Express {
interface Request {
currentUser: UserModel
}
}
}
Lets take a look again at our middleware file and we immediately notice that the red squiggly line is gone! This is because the Typescript compiler now recognizes the currentUser
property as a valid property on the Request type interface.
Happy Coding, everyone!
VS code doesn't show error in editor but during compilation i get:
currentUser does not exist on type 'Request'.
Its Ts error.