Express + Typescript: Hello, World
The Basics
I don’t often work on the server side, but recently I spent some time on a React Native project built with Typescript. Though React Native wasn’t a good fit the project we started, I was impressed with Typescript and enjoyed my time exploring the language. It’s got me thinking about what it would be like doing web service work with Typescript. In this series of posts, I’m going to spend some time exploring that and sharing my learnings.
Naturally, I’m going to start with a simple Hello, World project. Follow these steps and you’ll have a very simple web service built with Typescript.
Initialize your project
- Create new folder for your project:
mkdir helloworld && cd helloworld
- Initialize a new project with yarn:
yarn init -y
- Add Express:
yarn add express
Add Typescript
- Add Typescript dependencies:
yarn add --dev typescript @types/node @types/express
- Create
tsconfig.json
in the root of your project to specify the root file and compiler options that the Typescript compiler (tsc) will use. This snippet our source code is in thesrc
directory, build output should be placed in thebuild
folder. I’ve also addednoImplicitAny
option to tell the compiler to warn on any expressions or declarations with an impliedany
type because I want to get the benefits that Typescript’s types give me.
{
"compilerOptions": {
"outDir": "build",
"rootDir": "src",
"noImplicitAny": true,
}
}
Create the service
- Create your server file
mkdir src && touch server.ts
- Copy this into your new
server.ts
file:
import * as express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello, Typescript World'));
app.listen(port, () => console.log(`server running on port ${port}`));
Build and run your project
- Run
yarn tsc
to build your project. - Execute
node build/server.js
and browse to http://localhost:3000
Going further
Next time we’ll go a bit further and and automate the builds so that you don’t have to run build command every time you make change.