Book Image

TypeScript 4 Design Patterns and Best Practices

By : Theofanis Despoudis
Book Image

TypeScript 4 Design Patterns and Best Practices

By: Theofanis Despoudis

Overview of this book

Design patterns are critical armor for every developer to build maintainable apps. TypeScript 4 Design Patterns and Best Practices is a one-stop guide to help you learn design patterns and practices to develop scalable TypeScript applications. It will also serve as handy documentation for future maintainers. This book takes a hands-on approach to help you get up and running with the implementation of TypeScript design patterns and associated methodologies for writing testable code. You'll start by exploring the practical aspects of TypeScript 4 and its new features. The book will then take you through the traditional gang of four (GOF) design patterns in their classic and alternative form and show you how to use them in real-world development projects. Once you've got to grips with traditional design patterns, you'll advance to learning about their functional programming and reactive programming counterparts and how to couple them to deliver better and more idiomatic TypeScript code. By the end of this TypeScript book, you'll be able to efficiently recognize when and how to use the right design patterns in any practical use case and gain the confidence to work on scalable and maintainable TypeScript projects of any size.
Table of Contents (14 chapters)
1
Section 1: Getting Started with TypeScript 4
4
Section 2: Core Design Patterns and Concepts
8
Section 3: Advanced Concepts and Best Practices

Not using runtime assertions

TypeScript safety comes from compile-time checks when writing code. You define a type for a value and then TypeScript verifies its fair usage. This process, however, covers only 50% of the safety in general. The other 50% comes from runtime safety. For example, let's take the following function in TypeScript:

RuntimeAssertions.ts

function divMod(x: number, y: number): [number, number] {
  return [Math.floor(x / y), x % y];
}

This gets compiled in JavaScript as follows:

"use strict";
function divMod(x, y) {
    return [Math.floor(x / y), x % y];
}

Looking at the aforementioned code, you could guess that there are many potential dangers here:

  • The x and y parameters might not be numbers. If they are numbers encoded as strings, it will work but not if they are not a real number value:
    > divMod("1", 2)
    (2) [0, 1]
    > divMod("a", 2)
  • Here in the second case, we passed...