As a developer, we always want our code being bug-free. Or at least, we want to avoid the occurrence of the bugs because of our silly mistakes. Also, the code should be extensible, maintainable and highly readable that is as easy as reading plain English but not like looking at a mess of spaghetti.
Typescript is the superset of Javascript and it provides the following advantages:
Static Typed language allows the typing checking to be done during the coding phase of the development cycle such that the bugs can be found early. As Javascript is a dynamically typed language which does not perform typing checking so that some bugs may occur because of the implicit type conversion.
Typescript also enhanced the OOP feature of the Javascript, allowing the developer to use the “access modifiers” (private, public, protected) to control the accessibility of the data member in the class, to apply“inheritance” or define “interface” to improve the reusability of the code, and like the other OOP languages do, such as Java and C#.
That’s why Typescript can help us to achieve what we desired. Let get started to create your first Express.js Project using Typescript.
├── node_modules
├── package.json
├── package-lock.json
├── src
│ ├── controller
│ ├── model
│ └── test
└── tsconfig.json
In this demonstration, it is assumed that we want to build a lightweight and testable API server that serves for the requirements of the frontend clients. I personally prefer to use MVC architecture to divide the software into three main parts with different responsibilities. As the UI will be handled by the frontend clients, The “View” folder is not needed in the project.
npm init
2. Install the required package
npm i --save express @types/express typescript ts-node jest ts-jest supertest @types/supertest
Description of the packages
3. Create the tsconfig.json
This file is used to configure the Typescript compiler that transpile the Typescript code into Javascript. In this project, the following config will be used, the details of each configuration can be found here:
tsconfig.json
{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true
},
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules"
]
}
#programming #typescript #javascript #web-development #expressjs