Adjustments for TypeScript
Setup
Do the following as part of the setup for a TypeScript app:
- Generate
tsconfig
usingnpx tsc --init
- Enable
tsconfig
’soutDir
setting and set it to./dist
- this compiles your TypeScript code in that folder and runsindex.js
from there - Change the scripts in
package.json
:"build": "npx tsc"
"start": "node dist/index.js"
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\""
- Compile the app for the first time with
npm run build
- You can now launch the dev server with
npm run dev
without any errors
Working with Middleware
Middleware functions typically pass info down to the next middleware functions by adding properties to the request
object. However, you can only do this in TypeScript by extending the Request
type.
The way to do this in TypeScript is to extend the Request
type:
- In
src
, create atypes
folder with anexpress
folder in it. - Create a file
index.d.ts
in the foldertypes/express
. -
Add your required properties in the
index.d.ts
file:declare namespace Express { interface Request { yourNewProperty?: string; } }
- Add the
./types
(or./src/types
) folder into thetypeRoots
option intsconfig.json
.
Working with Mongoose Model Methods
It is possible to define custom methods on Mongoose models in vanilla JavaScript. However, once again, you can only do this in TypeScript by creating interfaces for your model methods.
Process:
-
Create an interface for the model’s methods.
interface IUserMethods { getName(): string; createJWT(): string; checkPassword(candidatePassword: string): boolean; }
-
Create a model type that recognises both (1) the interface for the schema and (2) the interface for the method(s):
type IUserModel = Model<IUserSchema, {}, IUserMethods>;
-
When defining the actual Mongoose
model
, specify the schema and type:const User = model<IUserSchema, IUserModel>('User', UserSchema)
For more examples, refer to the Mongoose documentation on TypeScript.