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

  1. Create new folder for your project: mkdir helloworld && cd helloworld
  2. Initialize a new project with yarn: yarn init -y
  3. Add Express: yarn add express

Add Typescript

  1. Add Typescript dependencies: yarn add --dev typescript @types/node @types/express
  2. 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 the src directory, build output should be placed in the build folder. I’ve also added noImplicitAny option to tell the compiler to warn on any expressions or declarations with an implied any type because I want to get the benefits that Typescript’s types give me.
{
  "compilerOptions": {
    "outDir": "build",
    "rootDir": "src",
    "noImplicitAny": true,
  }
}

Create the service

  1. Create your server file mkdir src && touch server.ts
  2. 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

  1. Run yarn tsc to build your project.
  2. 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.