The Fantastic 4: TypeScript features I’ve come to know and love

The chat interface

This article will showcase the usage of these four great features in the context of creating a chat app:

  • Async/Await
  • Union types
  • Type guards
  • Readonly properties

Async/Await

This feature enables you to define and call asynchronous code simply and concisely.

In the context of the chat app, users need to logon to the chat room via a network call. To keep the UI responsive you need to:

  1. Make the call asynchronously
  2. Inform the user that the logon is pending
  3. Update the UI once the user is successfully logged on as below:
Logon process

The code to carry this out is very straightforward:

Union types

This feature enables you to define a family of types using a lightweight syntax. You are able to do so without defining a class hierarchy.

In the context of the chat app it is used to define the kinds of messages that can be displayed in the chatbox:

The individual message types are defined as follows:

They all define a common property kind that you can use to determine what kind of message you are working with. In the example below every message type gets a template for display on the chat box depending on it’s kind.

Type guards

Type Guards allow you to narrow down the type of an object within a conditional block.

This feature is used to apply attributes to only those HTML elements that have them defined. For example, the href attribute defined for a subset of HTML elements.

An example usage is defined as below:

Readonly properties

TypeScript’s type system allows you to mark individual properties on an interface as readonly. This allows you to work in a functional way (unexpected mutation is bad).

All data containers defined in the chat app are immutable. A typical example is as below:

Parting shot

The complete source code can be found here. If you like the article kindly hammer the clap button. Thanks.

Acknowledgments

The HTML layout and CSS for the chat app are “borrowed” from this great project.

read original article here