Typescript.

Installing Typescript

Pre-requeisite

NPM

To install npm I like to do it with chocolatey (link to my blog post).

choco install nodejs -y

Install Typescript globally

npm install -g typescript

Once that is finished, let’s get the version of typescript returned to make sure it’s working correctly.

tsc -v

You should see the Version number output.

Install Typescript locally

VS Code will look at the local install, but also, people who clone our repo will have the correct version if we’ve installed it locally.

Create the package.json file

Let’s create a package.json file by running the following:

npm init -y

Add Typescript to the new package.json file

npm install --save-dev typescript@latest

This should now have added typescript to the devDependencies collection in your package.json file.

Execute the Typescript compiler

When we execute the Typescript compiler it transforms all the Typescript files into ES5 JavaScript files

Creeate a new file

Create a new file called server/server.ts

const message : string = "Hello World";
console.log(message);

Compile the file in to JavaScript

tsc server/server.ts

That will output a javascript into the same directory.

Run the Javascript file to test

node server/server.js

This will output Hello World to the terminal

Setup the TypeScript configuration

TypeScript is configured with a .tsconfig file

Create the tsconfig file

tsc --init

This will create the tsconfig json file in the current directory, with all the properties available in the file, but commented out.

Add property to list files

Now, we’re going to set the listEmittedFiles property to true, so that when we run tsc, we will see a list of the files that has been updated.

Add the following to your tsconfig file

"listEmittedFiles": true

Run tsc command

Now, let’s run the tsc command without any file name or options, and it should create the javascript file like before and list it in the terminal.

Install express

Install express via npm

npm install --save-dev express

Install express types

npm install --save-dev @types/express

Modify server.ts

Let’s modify our server.ts file to actually start the beginnings of a backend, by adding express.

Open up the server.ts file and delete the lines we created earlier and add the following:

import * as express from 'express';

const port : string | number = process.env.port  || 1337;

const app = express();

app.listen(port);

console.log("Listending on port " + port);

create index.html

create server .ts file and compile

server the app in the browswer