With TypeScript
Previously, we were using JavaScript with Express. But we can also use TypeScript with Express. In this blog, we will learn how to use TypeScript with Express. First of all, let's see what is TypeScript.
What is TypeScript?
TypeScript is a programming language that is used to write code for web applications, just like JavaScript. It is a superset of JavaScript, which means that all valid JavaScript code is also valid TypeScript code.
The main difference between TypeScript and JavaScript is that TypeScript adds a type system to the language. This means that TypeScript code can declare the types of variables, function parameters, and function return values. This can help catch errors in the code before it is executed, making the code more reliable and easier to maintain.
One important thing to note is that TypeScript code needs to be compiled into JavaScript to be run in a web browser or any other environment that supports JavaScript. This is because web browsers and other environments only understand JavaScript and not TypeScript. Therefore, developers use a TypeScript compiler to convert their TypeScript code into JavaScript code that can be executed in a web browser or any other environment that supports JavaScript. The resulting JavaScript code is often referred to as "transpiled" code.
Let's start
Create the folder typescript-express and run the following command to initialize the project.
- npm
- Yarn
- pnpm
- Bun
npm init -y
yarn init -y
pnpm init -y
bun init -y
It will create a package.json file.
Now, install the following packages.
- npm
- Yarn
- pnpm
- Bun
npm install express typescript
yarn add express typescript
pnpm add express typescript
bun add express typescript
You can also install typescript globally with the -g flag.
- npm
- Yarn
- pnpm
- Bun
npm install -g typescript
yarn global add typescript
pnpm add -g typescript
bun add --global typescript
However, it is not recommended to install packages globally. It is better to install packages locally.
Specifying Typescript Configuration
Typescript is not executed directly. It is first transpired into Javascript before it is executed. The transpiler will use the configurations specified in the typescript configuration file tsconfig.json to decide how to translate Typescript into Javascript. The file can be created manually in the project’s root directory. Or, you can create it via the terminal. If you have installed typescript locally, you can run the command below using npx:
npx tsc --init
Or if you installed typescript globally with the -g, you can run with the following command:
tsc --init
Either command will create the config file with default options in whichever directory you are currently in. Here is an example of the default tsconfig.json file:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es6"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Start Coding
Now you are ready to start developing your typescript application. To begin, create a src folder to put the application source in it.
Then, create a file index.ts in src. In the file, write the following code in.
import express, { Express, Request, Response } from "express";
const app: Express = express();
const port = 3000;
app.get("/", (req: Request, res: Response) => {
res.send("Hello, this is Express + TypeScript");
});
app.listen(port, () => {
console.log(`[Server]: I am running at https://localhost:${port}`);
});
We created index file with .ts extension. This is because we are using typescript. If we were using javascript, we would have created the file with .js extension.
Update package.json
Now, we can update the package.json to include the build and start command.
Add the following scripts
"build": "npx tsc""start": "node dist/index.js"
{
"name": "typescript-express",
"version": "1.0.0",
"description": "We can also use TypeScript with Express, in this doc, we will learn how to use TypeScript with Express.",
"main": "index.js",
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"typescript": "^4.2.4"
}
}
Build and Run
Now, we are ready to run the application. First, we need to transpile the application and get the index.ts translated into index.js in the /dist folder.
Run the following command in the terminal while you are in the project's root directory/folder to transpile the codes:
- npm
- Yarn
- pnpm
- Bun
npm run build
yarn build
pnpm run build
bun run build
The transpilation process will now start and after the transpilation is done, the project folder structure should now be updated to include a new file server.js in the dist folder like so:
📂 typescript-express
├── 📂 dist
│ └── 📄 index.js
├── 📂 node_modules
├── 📂 src
│ └── 📄 index.ts
├── 📄 package.json
└── 📄 tsconfig.json
Now, we can run the application by running the following command:
- npm
- Yarn
- pnpm
- Bun
npm run start
yarn run start
pnpm run start
bun run start
Once the server is up and running, you can go to your browser and access the URL: http://localhost:3000
Nodemon and ts-node
We can use nodemon and ts-node to run the application without building it first. Install the following packages.
- npm
- Yarn
- pnpm
- Bun
npm install nodemon ts-node
yarn add nodemon ts-node
pnpm add nodemon ts-node
bun add nodemon ts-node
Now, update the package.json to include the following scripts:
{
"name": "typescript-express",
"version": "1.0.0",
"description": "We can also use TypeScript with Express, in this doc, we will learn how to use TypeScript with Express.",
"main": "index.js",
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "nodemon --exec ts-node src/index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"typescript": "^4.2.4"
},
"devDependencies": {
"nodemon": "^2.0.7",
"ts-node": "^9.1.1"
}
}
Now, we can run the application by running the following command:
- npm
- Yarn
- pnpm
- Bun
npm run dev
yarn dev
pnpm run dev
bun run dev
Conclusion
In this blog, we learned how to use typescript with express. We also learned how to use nodemon and ts-node to run the application without building it first.