TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. Express is a minimal and flexible Node.js web application framework that provides robust features for web and mobile applications. Together, they are commonly used to deploy powerful web pages and applications.
TypeScript and Express
TypeScript supports static typing, interfaces, features prototyping, modules, etc., but javascript doesn't. This means that JavaScript is better suited for small-scale applications, while TypeScript is better for larger applications. Moreover, errors can be found and fixed at compile time in TypeScript. This makes TypeScript useful in today's applications.
There is no hard time switching to TypeScript from JavaScript. Therefore, we are getting on with TypeScript for this tutorial.
I assume you've already installed Nodejs. If not, you can install it for your Operating System from its official site.
Now let's begin!
Creating the Project
First of all, let's create a project directory. Let's name it express (or whatever else you prefer).
Open a terminal in that directory and initiate a node project by typing the command:
It will ask a bunch of fields to insert for the basic information about your project. Insert what you like, or let it be.
Now, let's install typescript and express using the command :
Let's initialize the typescript config for the project using the command :
It will create a node_modules folder in the project directory, along with package.json, package-lock.json and tsconfig.json files. You can configure typescript settings by modifying the tsconfig.json file.
For now, you can use my config to keep the project running.
Now let's create a directory called src and our main file index.ts inside src. You can do it in your code editor, using file manager, or by running the command :
Coding
So far, we have created our project with working directory src. Now let's code.
Edit your index.ts file to be:
With the code above, we are using Express to create the default and jr routes. The default routes send a text message, whereas the jr route sends a json.
Let's compile the typescript according to our typescript config file tsconfig.json:
It will create a dist folder inside the project directory which contains the compiled javascript code. The src folder was compiled and outputted to the dist folder based on our tsconfig.json.
Now, we can run the project using:
node dist/index.js
Hit http://127.0.0.1:3000 and http://127.0.0.1:3000/jr in your browser and check the result. The default route will show the text "Welcome to Texpress" in your browser, and the jr route will send you the json given in the code.
This is just a basic how-to with typescript and express. Hope it helped!