Real Time Apps with TypeScript: Integrating Web Sockets, Node & Angular

Building a Real Time Chat app from scratch using TypeScript

Some time ago I implemented a simple chat application using TypeScript language only. The main goal was to write a demo to explain how you can use this programming language on the client side and on the server. The client app is using latest Angular features.

In this post I will show you how I implemented the app from scratch.

Demo: TypeScript Chat Application

What is a Real Time Application?

According this Wikipedia definition, a real-time application allows information to be received as soon as it is published, rather than requiring a source to be checked periodically for updates. Therefore, this kind of app should give a feeling to users that events and actions happen immediately.

WebSockets

WebSockets is a protocol that provides a bi-directional communication channel. This means that a browser and web server can maintain real-time comms, sending messages back and forth while the connection is open.

Websockets communication

Application Structure

We will separate server related code and client code. I will go into details when most important files will are explained. For now, this is the expected structure of our application:

server/

|- src/

|- package.json

|- tsconfig.json

|- gulpfile.js client/

|- src/

|- package.json

|- tsconfig.json

|- .angular-cli.json

Server Code

Since WebSockets is a specification, we can find several implementations about it. We can choose J̶a̶v̶a̶S̶c̶r̶i̶p̶t̶ TypeScript or any other programming language.

In this case we’ll use Socket.IO, which is one of the fastest and most reliable real-time engines.

Why use TypeScript on server side code?

TypeScript comes with really cool features and it is updated very often. It can prevent about 15% of bugs. Do you need more reasons? 😄

Initializing server application

Create a package.json file and then install the following dependencies:

npm install --save express socket.io @types/express @types/socket.io

We’ll need to install some devDependencies to allow integrate gulp and typescript so that we can define build tasks easily with these tools later:

npm install --save-dev typescript gulp gulp-typescript

TypeScript Compiler Configuration

Create a tsconfig.json file with the following content:

Data Model definition

Taking advantage of static typing, let’s define a small data model as follows:

..let’s see further details into our server/src directory:

server/

|- src/

|- model/

|- message.model.ts

|- user.model.ts

|- index.ts

|- server.ts

|- package.json

|- tsconfig.json

|- gulpfile.js

Chat Server Implementation

The main files in server directory are index.ts and chat-server.ts . The first one allows us to create and export our ChatServer app, while the last one contains express and socket.IO configurations:

Server Classes

The previous code will give a result of the following classes and relationships: