Hands-On Functional Programming with TypeScript - Remo H. Jansen - E-Book

Hands-On Functional Programming with TypeScript E-Book

Remo H. Jansen

0,0
32,36 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Discover the power of functional programming, lazy evaluation, monads, concurrency, and immutability to create succinct and expressive implementations




Key Features



  • Get a solid understanding of how to apply functional programming concepts in TypeScript


  • Explore TypeScript runtime features such as event loop, closures, and Prototypes


  • Gain deeper knowledge on the pros and cons of TypeScript






Book Description



Functional programming is a powerful programming paradigm that can help you to write better code. However, learning functional programming can be complicated, and the existing literature is often too complex for beginners. This book is an approachable introduction to functional programming and reactive programming with TypeScript for readers without previous experience in functional programming with JavaScript, TypeScript , or any other programming language.







The book will help you understand the pros, cons, and core principles of functional programming in TypeScript. It will explain higher order functions, referential transparency, functional composition, and monads with the help of effective code examples. Using TypeScript as a functional programming language, you'll also be able to brush up on your knowledge of applying functional programming techniques, including currying, laziness, and immutability, to real-world scenarios.







By the end of this book, you will be confident when it comes to using core functional and reactive programming techniques to help you build effective applications with TypeScript.






What you will learn



  • Understand the pros and cons of functional programming


  • Delve into the principles, patterns, and best practices of functional and reactive programming


  • Use lazy evaluation to improve the performance of applications


  • Explore functional optics with Ramda


  • Gain insights into category theory functional data structures such as Functors and Monads


  • Use functions as values, so that they can be passed as arguments to other functions





Who this book is for



This book is designed for readers with no prior experience of functional programming with JavaScript, TypeScript or any other programming language. Some familiarity with TypeScript and web development is a must to grasp the concepts in the book easily.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 217

Veröffentlichungsjahr: 2019

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Hands-On Functional Programming with TypeScript

 

 

Explore functional and reactive programming to create robust and testable TypeScript applications

 

 

 

 

 

 

 

 

 

Remo H. Jansen

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Hands-On Functional Programming with TypeScript

Copyright © 2019 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Richa TripathiAcquisition Editor: Denim PintoContent Development Editor: Anugraha ArunagiriTechnical Editor: Ashi SinghCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Rekha NairGraphics: Tom ScariaProduction Coordinator: Saili Kale

First published: January 2019

Production reference: 1290119

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78883-143-7

www.packtpub.com

To Lorraine, for being my sword in my victories and my shield in my defeats. Without your support, I wouldn't be where I am and I wouldn't be the person I am today. Thank you!

– Remo H. Jansen

 
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. 

Foreword

When TypeScript was officially announced on October 1, 2012, the only docs available was the dense official language specification. It was not easily accessible to beginner developers as there was significant focus on syntax. Additionally, it assumed an existing intimate knowledge of JavaScript. Nevertheless, it was complete in terms of TypeScript features at the time, and JavaScript was not as feature-rich as it is today. So, it was a plausible entry point into TypeScript, and that is what I and many others at the time used to learn TypeScript.

How times have changed. Over time, TypeScript has gained a number of features, and so has JavaScript. Keeping up to date now means following relevant GitHub issues and pull requests on Microsoft/TypeScript and reading up on the understanding offered by key developers. Remo is one of those key developers. I got introduced to Remo through his insightful comments on TypeScript issues and then discovered his blog (blog.wolksoftware.com). Remo's blog has been a great help in dissecting important features such as JavaScript decorators and explaining how they are implemented in TypeScript. I find myself linking fellow developers to his docs instead of the alternatives due to the high quality of his work.

Not only has Remo been a great help in understanding TypeScript (and JavaScript), but he has also been a great asset to the TypeScript library ecosystem. One question that I commonly receive from developers is how to do dependency injection in TypeScript. My answer is always a direct link to Remo's extremely useful InversifyJS library (inversify.io).

One of the key concerns that uninformed developers have had about TypeScript is "it only supports object-oriented programming." That is simply not true. TypeScript supports all JavaScript paradigms, and functional programming has first-class support. In fact, it provides a vital piece of famous functional programming languages (compile-time type information) for JavaScript developers.

All programming tasks can be considered as simple (data plus data transformation). This is the mental model encouraged by functional programming aficionados. To have a deep understanding of functional programs as a data transform pipeline, you need a way to define your data structures. This is what is only provided by TypeScript. In the absence of TypeScript, you see various (somewhat arbitrary) syntax elements used to describe the data structures that are flowing through your functional programs.

So, if you want to do world-class functional programming and your programming environment forces you (if only by convenience) to use JavaScript, please consider TypeScript and know that you are not alone. Remo H. Jansen is here to help you.

 

Basarat Ali Syed

Microsoft MVP and one of the leading global references of the TypeScript community.

Contributors

About the author

Remo H. Jansen lives in Dublin, Ireland, where he works as the managing director of Wolk Software Limited and as a part-time lecturer at CCT College Dublin. Remo is a Microsoft MVP and an active member of the TypeScript community. He is the author of Learning TypeScript 2.x, organizes the Dublin TypeScript and Dublin OSS meetups, writes a blog, and maintains some open source projects on GitHub. Remo is available for conference talks, independent consulting, and corporate training services opportunities.

Thanks to everyone who participated in this book for your support and hard work: my friends, Lorraine, and my family, for your support and patience, and to the TypeScript teams and its contributors for creating what has become my favorite programming language.

About the reviewers

Gaurav Aroraa has an M.Phil in computer science. He is a Microsoft MVP, a lifetime member of Computer Society of India (CSI), an advisory member of IndiaMentor, certified as a Scrum trainer/coach, XEN for ITIL-F, and APMG for PRINCE-F and PRINCE-P. He is an open source developer, a contributor to TechNet Wiki, and the founder of Ovatic Systems Private Limited. In the more than 20 years of his career, he has mentored thousands of students and industry professionals. You can tweet Gaurav using his Twitter handle, @g_arora.

To my wife, Shuby Arora, and my angel (daughter), Aarchi Arora, who permitted me to steal time for this book from the time I was supposed to spend with them. Thanks to the entire Packt team, especially Ulhas and Anugraha Arunagiri, whose coordination and communication during the period was tremendous, and Denim Pinto, who introduced me for this book.

 

 

Sergio PachecoJimenez is a Software engineer residing in Seville, Spain. He is mainly focused on .NET, JavaScript and web development. For the last few years, he has been using and advocating TypeScript. Currently, he is working on the banking industry.

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Hands-On Functional Programming with TypeScript

Dedication

About Packt

Why subscribe?

Packt.com

Foreword

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Functional Programming Fundamentals

Is TypeScript a functional programming language?

The benefits of functional programming

Introducing functional programming

Pure functions

side-effects

Referential transparency

Stateless versus stateful

Declarative versus imperative programming

Immutability

Functions as first-class citizens

Lambda expressions

Function arity

Higher-order functions

Laziness

Summary

Mastering Functions

Function types

Named and anonymous functions

Function declarations and function expressions

Working with function parameters

Trailing commas in function arguments

Functions with optional parameters

Functions with default parameters

Functions with rest parameters

Function overloading

Specialized overloading signature

Function scope and hoisting

Immediately-invoked functions

Tag functions and tagged templates

Summary

Mastering Asynchronous Programming

Callbacks and higher-order functions

Arrow functions

Callback hell

Promises

Covariant checking in callback parameters

Generators

Asynchronous functions – async and await

Asynchronous generators

Asynchronous iteration (for await…of)

Delegating to another generator (yield*)

Summary

The Runtime – The Event Loop and the this Operator

The environment

Understanding the event loop

Frames

Stack

Queue

Heap

The event loop

The this operator

The this operator in the global context

The this operator in the function context

The call, apply, and bind methods

Summary

The Runtime – Closures and Prototypes

Prototypes

Instance properties versus class properties

Prototypal inheritance

Prototype chains and property shadowing

Accessing the prototype of an object

Closures

Static variables powered by closures

Private members powered by closures

Summary

Functional Programming Techniques

Composition techniques

Composition

Partial application

Currying

strictBindCallApply

Pipes

Other techniques

Point-free style

Recursion

Pattern matching

Summary

Category Theory

Category theory

Functors

Applicative

Maybe

Either

Monads

Summary

Immutability, Optics, and Laziness

Immutability

Optics

Lenses

Prisms

Laziness

Summary

Functional-Reactive Programming

Reactive programming

Functional programming versus functional-reactive programming

The benefits of functional-reactive programming

Working with observables

The observer pattern

The iterator pattern

Creating observables

Creating observables from a value

Creating observables from arrays

Creating observables from events

Creating observables from callbacks

Creating observables from promises

Cold and hot observables

Working with operators

Pipe

Max

Every

Find

Filter

Map

Reduce

Throttle

Merge

Zip

Summary

Real-World Functional Programming

Working with Ramda

Composition

Partial application and currying

Lenses

Working with Immutable.js

Working with Immer

Working with Funfix

Summary

Functional Programming Learning Road Map

Beginner

Advanced beginner

Intermediate

Proficient

Expert

Summary

Directory of TypeScript Functional Programming Libraries

Functional programming

Category theory

Laziness

Immutability

Optics and lenses

Functional-reactive programming

Others

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. The origins of the functional programming paradigm can be traced back to the 1930s when Alonzo Church introduced Lambda calculus. Lambda calculus presents a theoretical framework for describing functions and their evaluation, and is a mathematical abstraction rather than a programming language. However, Lambda calculus is the foundation of most functional programming languages.

In the late 1950s, Lisp, one of the first functional programming languages, was developed by John McCarthy. Lisp introduced many functional programming paradigm features, and it was the primary influence of other popular functional programming languages, such as Scheme and Clojure.

In 1973, Robin Milner created ML at the University of Edinburgh. ML eventually developed into several alternative languages, the most common of which are now OCaml and Standard ML. In 1977, John Backus defined functional programs in a way that allows an "algebra of programs" and follows the principle of compositionality. In 1985, Research Software Limited released Miranda, and the interest in lazy functional programming languages grew. After a couple of years, more than a dozen non-strict, purely functional programming languages existed. In 1987, at the conference on functional programming languages and computer architecture in Portland, Oregon, there was a strong consensus that a committee should be formed to define an open standard for such languages; Haskell was born.

The 1970s and 1980s were years of significant advancement for functional programming. However, during the 1990s and 2000s, functional programming lost market share against object-oriented programming languages, such as Java and C#.

In the 2010s, the adoption of JavaScript grew exponentially, and it became the most popular programming language. The Scheme programming language is one of the main influences of JavaScript and, as a result, JavaScript implements many functional programming features, such as support for higher-order functions. JavaScript became the first contact with functional programming for many young developers. However, because JavaScript is a multi-paradigm programming language, many ignored its functional programming capabilities. However, in recent times, thanks to the arrival of technologies highly influenced by functional programmings principles, such as React, RxJS, and Redux, there has been a significant increase in interest in functional programming within the JavaScript community.

As the popularity of JavaScript grew, the complexity of JavaScript applications also grew exponentially. Web user interfaces became much more sophisticated, and JavaScript started to be used in a number of alternative scenarios, such as backend applications. The TypeScript programming language was then introduced as a tool that allows us to manage the new levels of complexity.

TypeScript aims to reduce the complexity of a system by adding a static type system to JavaScript. Static type systems can be used to detect errors at compilation time as a beneficial form of in-code documentation. Static type systems can be very beneficial in functional programming. Most object-oriented programming languages, such as Java and C#, are slowly adopting functional programming features, and sophisticated static type systems are something that is many times associated with purely functional programming languages, such as Haskell.

This book is not going to encourage you to stop using object-oriented programming. Instead, we are going to try to think about both the functional programming and the object-oriented programming paradigms as two different solutions to the same problem: managing complexity:

"Object-oriented programming makes code understandable by encapsulating moving parts. Functional programming makes code understandable by minimizing moving parts."

– Michael Feathers

The popularity of distributed systems is increasing as the adoption of cloud computing continues to grow and, as a result, functional programming is expected to rise in popularity over the next decade because it is particularly well suited for concurrent systems and distributed systems. Functional programming encourages the implementation of stateless components, which can be scaled with ease. Since the complexity of distributed systems is usually high, this is just another example of how functional programming can be used as a weapon against complexity.

Mastering TypeScript together with the principles and techniques of both object-oriented programming and functional programming can provide us with a richer toolset to fight against complexity in our systems. This book will provide you with knowledge about a wide range of functional programming principles, patterns, and techniques that should help you to become a more versatile software engineer and prepare you for dealing with the increasing complexity in modern web applications.

Who this book is for

If you are a developer aiming to learn functional programming for the very first time and improve the quality of your applications, then this book is for you. No prior knowledge of functional programming is required. However, a basic understanding of JavaScript and TypeScript is recommended to make the most out of this book.

What this book covers

Chapter 1, Functional Programming Fundamentals, introduces the main functional programming terms, such as pure functions.

Chapter 2, Mastering Functions, takes an in-depth look at the main building block in a functional programming application—functions. The chapter also explores most of the function-related features in TypeScript. We will learn how to work with functions in many different scenarios and how to take advantage of the TypeScript type system features while working with functions.

Chapter 3, Mastering Asynchronous Programming, takes an in-depth look at the main asynchronous programming APIs in JavaScript and TypeScript, including callbacks, promises, generators, and asynchronous functions. These APIs are relevant in functional programming because they can be used to implement lazy evaluation.

Chapter 4, The Runtime – The Event Loop and the this Operator, is the first chapter of two that are dedicated to exploring concepts about the runtime that are relevant for a number of functional programming techniques. For example, we can gain a much better understanding of recursion if we understand the event loop.

Chapter 5, The Runtime – Closures and Prototypes, is the second chapter dedicated to exploring concepts about the runtime that are relevant to a number of functional programming techniques. For example, understanding closures can help us to understand how some higher-order functions work.

Chapter 6, Functional Programming Techniques, explores the main functional programming techniques and patterns in detail. We will explore concepts such as partial function application, functional composition, and currying. This chapter also explores many other functional programming techniques and patterns, such as point-free style.

Chapter 7, Category Theory, explores category theory. You will learn about what algebraic data types are and what the relationships between them are. You will then learn how to implement some of the main algebraic data types, including functors and monads.

Chapter 8, Immutability, Optics, and Laziness, explores three important functional programming techniques. You will learn about what lazy evaluation is, what its benefits are, and how to implement it. You will also learn about immutable data structures, their benefits, and how to implement them. Finally, you will learn about functional optics and how they can help with immutable data structures.

Chapter 9, Functional-Reactive Programming, explores the functional-reactive programming paradigm. We will learn about what observables are and how they can be used to simplify our code. We will also learn how to use RxJS, the leading reactive-programming library in the JavaScript ecosystem.

Chapter 10, Real-World Functional Programming, explores some production-ready functional programming libraries, such as Ramda and Funfix, to create real-world functional programming applications.\

Appendix A, Functional Programming Learning Road Map, this was developed for Fantasyland institute of learning for the LambdaConf conference. It is used to track our level of knowledge regarding functional programming.

Appendix B, Directory of TypeScript Functional Programming Libraries, In this appendix, you will find a list of functional programming libraries compatible with TypeScript grouped.

To get the most out of this book

You don't need any additional material to follow this book. No prior knowledge of functional programming is required. However, a basic understanding of JavaScript and TypeScript is recommended to make the most use of this book.

It is recommended reading the chapters in order. However, if you are new to functional programming and already have advanced knowledge of functions, asynchronous programming, and the runtime, you could maybe skip chapters two to five.

You can refer to the TypeScript handbook at http://www.typescriptlang.org/docs/handbook/basic-types.html if you have some experience with JavaScript, but TypeScript is new to you. This resource might be especially useful if TypeScript is your first statically typed programming language. Alternatively, you can refer to the book Learning TypeScript 2.x, Second Edition, also by Remo H. Jansen and Packt Publishing.

If you need help installing Node.js, you can refer to the official documentation at https://nodejs.org/en/download/package-manager. If you need help installing TypeScript, you can refer to the official documentation at http://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packt.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Functional-Programming-with-Typescript. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781788831437_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Functional Programming Fundamentals

JavaScript has been a multi-paradigm programming language since its inception back in 1995. It allows us to take advantage of an object-oriented programming (OOP) style along with a functional programming style. The same can be said of TypeScript. However, for functional programming, TypeScript is even better suited than JavaScript because, as we will learn in this chapter, static type systems and type inference are both very important features in functional programming languages such as the ML family of programming languages, for example.

The JavaScript and TypeScript ecosystems have experienced a significant increase in interest in functional programming over the last few years. I believe that this increase in interest can be attributed to the success of React. React is a library developed by Facebook for building user interfaces, and it is highly influenced by some core functional programming concepts.

In this chapter, we will focus on learning some of the most basic functional programming concepts and principles.

In this chapter, you will learn about the following:

The main characteristics of functional programming

The main benefits of functional programming

Pure functions

side-effects

Immutability

Function arity

Higher-order functions

Laziness

Is TypeScript a functional programming language?

The answer to this question is yes, but only in part. TypeScript is a multi-paradigm programming language and, as a result, it includes many influences from both OOP languages and functional programming paradigms.

However, if we focus on TypeScript as a functional programming language, we can observe that it is not a purely functional programming language because, for example, the TypeScript compiler doesn't force our code to be free of side-effects.