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 6: Functional Programming with TypeScript

In this chapter, we'll start exploring some programming paradigms that are available in the TypeScript language, starting with functional programming. The key difference here compared to design patterns is that concepts of functional programming are primarily the building blocks of programming patterns and can be synthesized in various forms. Functional programming is a programming paradigm whose key concepts are expressions, function composition, recursion, immutability, purity, and referential transparency. Using these concepts together like higher-order functions allows you more flexibility when designing applications.

You will discover how those concepts come to life with TypeScript and how to build advanced structures such as monads or transducers to produce larger programs without sacrificing type safety.

In this chapter, we will cover the following topics:

  • Learning key concepts in functional programming
  • ...

Learning key concepts in functional programming

The term programming paradigm refers to putting certain concepts and rules under a framework that you can use to design programs and algorithms. The term functional programming relates to a programming paradigm that uses functions as the main building blocks to form large computer programs.

We'll make a distinction now between what we have learned so far about design patterns and what we will learn now about design concepts as they have a different meaning.

Design concepts are the building blocks of any programming paradigm. For example, the basic concepts of Object-Oriented Programming (OOP) are encapsulation, abstraction, inheritance, and polymorphism. If you don't have encapsulation, then you can't protect access to private object members, making it difficult to apply certain design patterns.

Under the functional programming paradigm, there are key concepts that you have to use to gain maximum benefits. We...

Understanding functional lenses

A functional lens is another name for an object's getter and setter methods paired together in a tuple. We call them like that mainly because the idea is to have a functional way to compose getters and setters without modifying an existing object. So, you use a lens to create scopes over objects, and then you use those scopes if you want to interface with the objects in a composable way.

You can think of lenses as similar to having an Adapter pattern where the Target is the object you want to adapt and the lenses are the Adaptees. You create lenses that adapt over an object type and you can get or set their properties. The main benefit here is that the Lenses object is generic and you can compose it in a functional way.

Let's explain more about lenses next and how to implement them in TypeScript.

Implementation of lenses

A basic lens interface supports two methods: Get is for getting a property of type A from an object of type T...

Understanding transducers

Transducers are another name for reducers that take an input and return another reducer, forming a composition between them. To understand why this is helpful, we'll explain the basics of reducers first.

A reducer is a simple function that accepts an input of type T, which is typically a collection. It is a function that accepts the current value in the collection, the current aggregated value, and a starting value. The job of the reducer is to iterate over the collection starting from the initial value, calling the function that accepts the current aggregate and the current iteration and returns the end result.

Here is an example reducer in TypeScript:

Transducer.ts

const collection = [1, 2, 3, 4, 5];
function addReducer(curr: number, acc: number): number {
  return curr + acc;
}
console.log(collection.reduce(addReducer, 0));

This reducer function has the type (number, number): number and the reduce method accepts the reducer...

Understanding monads

A monad is an object that adheres to specific rules and laws and allows the composition of other types of monads using a common API.

You can think of the monad as an object that exposes a set of methods that make it easier to compose other monads of the same type together. Usually, an object called a monad needs to follow what we call monadic laws, which we will explain later.

The main function of a monad is to allow the chaining of operations of any type of function, examine its value, extract it if it's a composite, perform the operation, and enclose it again in the same nested object.

It's quite hard to understand what a monad really is because it assumes you already know what a monad is, so we are going to explain what problems they solve. Hopefully, you will understand their value and how monads can be used to compose programs of any type.

We'll take the example function composition that we described previously. For two functions...

Summary

Within this chapter, we explored the fundamental concepts of functional programming and explored some practical examples. Those concepts constitute the backbone of functional programming in general.

We started by understanding the concepts of purity, function composition, and immutability. We noted practical examples of recursion and discovered the benefits of referential transparency. We resumed our exploration with practical functional programming constructs, starting with lenses, which form an abstraction over getters and setters, after which, we learned how transducers can be used to process infinite streams of data in a chain without loss of performance. Finally, we looked at monads and their crucial helpfulness in constructing composable structures at scale.

Utilizing these concepts will support you in structuring your code in a pleasant, abstract way with scalability in mind. In the subsequent chapter, you will learn how reactive programming can help us deliver...

Q & A

  1. How does functional programming differ from object-oriented programming?

    While both functional programming and OOP aim to provide bug-free and nicely coded structures, they approach the problem differently. With functional programming, you use functions as first-class citizens and apply function composition to deliver programs. With OOP, you use classes and objects to create abstractions and leverage design patterns to manage their communication type or structure.

  2. Is calling a function that checks the browser's local storage safe to use in functional programming and why?

    No. Unless the function is capturing this operation in an IO effect, it can break purity. This also means that referential transparency is also affected, making it hard to figure out sources of problems, especially when your whole application is composed of functions.

  3. Are Higher-Order Functions (HOFs) part of functional programming concepts?

    Yes. HOFs are functions that take a function as...

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