Why do we want to use Typescript?

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
  • Enhanced Object Oriented Programming Features

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.

Project Overview

├── 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.

  1. Create package.json
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

  • expressThe web framework for our server
  • @types/expressThe typescript definition of express
  • typescriptThe language pack of Typescript
  • ts-nodeTypeScript execution and REPL for node.js
  • jestJavaScript Testing Framework for unit testing
  • ts-jestTypeScript preprocessor of jest

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

How to Kickstart Your First Express.js Project With Typescript?
1.25 GEEK