v6
In this example, we will guide you through the steps to turn your project into a TypeScript project. After the guide have been completed, you will benefit from strong type checking and code completion.
Use this example only for versions under 6
Requirements
In this example, we will assume that you are familiar with TypeScript and that you have it installed.
If this is not the case, simply run the following to get packages you will need in this Woodshop: npm install --save-dev typescript tsc-watch nodemon
To make it easy for you, we created our own typings to help you using our exposed tools using TypeScript. They are available as @types/forest-express-sequelize
and @types/forest-express-mongoose
.
To get them, simply run: npm install --save-dev @types/forest-express-[sequelize | mongoose]
Configuration
As for every TypeScript project, we need to create a configuration file. It helps the transpiler to know where to take the files from, and where to transpile them to. To have a smooth migration into TypeScript, we will use the following configuration:
Add this file at the root of your project.
This tells the transpiler to take every file using .ts
or .js
(see allowJs
option) as an extension, and to transpile them into a ./dist
folder. This is where your transpiled files will be. This type of configuration allows you to translate your app into TypeScript in dribs and drabs. No need to translate every file at once, change only the files that interest you.
Now that your TypeScript transpiler is set, we need to update our .package.json
with new scripts to fit with the new structure of our project.
Note the last script start-dev
is the script to use while developing. It will transpile your sources every time you perform a change, and it will refresh your server.
Finally, let's install the mandatory typings for a newly generated project, run this from a command prompt:
And that's it!
You are now able to code using TypeScript in your app. Simply change the extension from .js
to .ts
, change some code, and your file will be automatically handled.
How it works
Directory: /models
Depending on your ORM (sequelize, mongoose) your models' configuration will change.
Sequelize Models
The idea here is to create a TypeScript class which will describe how your data should look like, and then init your actual model using sequelize.
Let's take a simple user
model, generated by Lumber:
Let's create a TypeScript class to describe our data, based on this model. Create a folder alongside models
to store interfaces, and create the users.ts
interfaces: