Reader small image

You're reading from  TypeScript 4 Design Patterns and Best Practices

Product typeBook
Published inSep 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781800563421
Edition1st Edition
Right arrow
Author (1)
 Theofanis Despoudis
Theofanis Despoudis
author image
Theofanis Despoudis

Theo Despoudis lives in Ireland, where he works as a Software Engineer for WP Engine and as a part-time tech practitioner for Fixate. He is the co-author of The React Workshop and Advanced Go Programming in 7 Days, Dzone Core Member, and maintains some open source projects on GitHub. Theo is available for conference talks, independent consulting, and corporate training services opportunities.
Read more about Theofanis Despoudis

Right arrow

Chapter 2: TypeScript Core Principles

Until now we've discussed the basic programming constructs of TypeScript, for example, basic types such as interfaces, classes, and enums. Although you can write fully fledged programs in principle with only those types, in practice, we rely on higher-order abstractions and type utilities.

Learning more about advanced types, namely types that model a more accurate representation of objects for the compiler to check, helps in making your code short, concise, and readable. Additionally, using an Object-Oriented Programming (OOP) style, you can create more cohesive abstractions that use objects and allow operations to model the real world.

This chapter will assist you in explaining the origins of design patterns and how they are related but not restricted to OOP, as a way to work around some limitations and look forward to learning about them in more detail in subsequent chapters.

In this chapter, we are going to cover the following...

Working with advanced types

Our exploration into TypeScript does not end with basic types. TypeScript offers more advanced ways to model types and you will encounter them quite often in production code. By learning what they are and how they work, you can combine them to produce more accurate transformations. Let's start by learning about some common utility types.

Using utility types

When you define the TypeScript compilation target, for example, ES5, ES6, and so on, then the compiler includes a relevant global definition file with an identical name, for example, lib.es5.d.ts or lib.es6.d.ts. Those files contain common utility types for you to use in your applications. We will now explore the most significant utilities and how to put them into practical use:

  • Record: If you want to define an object type that contains property keys taken from a specific type and values from another, you should use Record. A common use case is when you want to declare configuration...

OOP with TypeScript

TypeScript supports multiple programming paradigms. A programming paradigm is a way that a language supports and promotes language features such as immutability, abstractions, or function literals.

OOP is a programming paradigm where objects are first-class citizens. Objects are a concept that we use to describe things that contain data and ways to retrieve the data. Usually, you try to design objects that model the real world or a domain primitive. For example, if you are trying to model a real user into a type, then we create a User class containing the data that you want to capture for that user.

The four principles of OOP are encapsulation, abstraction, inheritance, and polymorphism. We'll start explaining those principles one by one.

Abstraction

Abstraction is a way of having implementation details hidden from the client or the user of an object. You can implement abstract entities to provide an interface of allowed operations and then we can...

Developing in the browser

TypeScript was created as a superset of JavaScript and to provide useful facilities to catch mistakes early and make JavaScript development safer and scalable. JavaScript is a language of the browser, therefore when working with TypeScript in the browser, you have to understand this particular environment. This means you must understand the Document Object Model (DOM) API, how to respond to user events, and how to avoid pitfalls in the process. Also, utilizing a bundler such as webpack helps you automate the process of compiling and minimizing assets in the production environment. Using a UI framework such as React can help you to build interactive applications using a component-based architecture.

First, you want to understand how to work with the DOM.

Note

Some of the examples cannot work when using Node.js as they depend on the global window object, so you will need to use a modern browser such as Chrome or Firefox.

Understanding the DOM

...

Developing in the server

Now that you know the basics of application development in the browser, you can expand your knowledge into the server side. When working on the server, you have different challenges to solve and because of that, you will have to approach them differently.

It's not that it's more difficult to work in the server compared to the browser, but the approach of those solutions may not be appropriate for all use cases. You may also find that security is more paramount in server environments as they interface with databases that can store private data, secrets, and sensitive or personal information.

Understanding the server environment

In general, when working on the server, you have application code that serves requests over a port (TCP, UDP, or other protocol). A typical case is with an HTTP server but it can be anything in between from internal microservices to internal tools, daemons, and so on. We can identify the following key considerations...

Introducing design patterns in TypeScript

You have explored how to develop server-side applications in TypeScript and now you are ready to study design patterns in detail one by one. We can conclude this chapter by introducing design patterns and grasping why they are still relevant today.

Since the original design patterns book that was published in 1994, many engineering practices have changed. This does not mean they should be devalued as anachronistic or irrelevant. Preferably, they should be regarded and evaluated in terms of the current programming language criteria and best practices.

Why design patterns exist

A design pattern by definition is a systematic and repeatable solution for combating recurring problems when constructing software applications. Developing software is regarded as a very complex and sophisticated operation and there are many right or wrong ways to do it properly. It completely depends on the problem you require to resolve or what is required to...

Summary

The advanced language primitives discussed throughout this chapter are really helpful language features when it comes to defining the exact types in our abstractions.

If you work with TypeScript and adhere to OOP principles, you will find that some abstractions lead to low-coupled code, while others such as inheritance achieve the opposite as they can increase code coupling if modeled incorrectly.

TypeScript is a truly multi-paradigm language that can be used equally successfully in the browser and the server environment. However, it's significant to understand that each environment presents different challenges, so they call for alternative approaches.

By learning about design patterns, you can understand how those proven and reliable concepts designed by software experts can help manage complexity at scale whether we use OOP or any other programming style.

In the next chapter, you will gain a more in-depth understanding of design patterns as you start learning...

Q&A

  1. Why is inheritance considered an antipattern sometimes?

    Inheritance increases the coupling between the parent and child classes as it makes it more difficult to change the parent class without affecting the children.

  2. What is polymorphism?

    Polymorphism is an OOP concept that allows us to use a single interface or object to perform different things. Polymorphism promotes extensibility by using this flexible approach of either method overloading or having an interface sending a message to different objects at runtime.

  3. Why have design patterns stood the test of time and are still used today?

    Design patterns are common solutions to problems that were originally encountered when working with OOP languages. They have stood the test of time because they tend to appear, quite often, as a logical result of refactoring or when trying to reuse certain abstractions.

  4. What are the main differences between writing server-side code versus frontend code?

    Frontend code uses HTML...

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
TypeScript 4 Design Patterns and Best Practices
Published in: Sep 2021Publisher: PacktISBN-13: 9781800563421
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Theofanis Despoudis

Theo Despoudis lives in Ireland, where he works as a Software Engineer for WP Engine and as a part-time tech practitioner for Fixate. He is the co-author of The React Workshop and Advanced Go Programming in 7 Days, Dzone Core Member, and maintains some open source projects on GitHub. Theo is available for conference talks, independent consulting, and corporate training services opportunities.
Read more about Theofanis Despoudis