📄 Page
1
M A N N I N G YAKOV FAIN ANTON MOISEEV
📄 Page
2
TypeScript Quickly YAKOV FAIN AND ANTON MOISEEV M A N N I N G SHELTER ISLAND
📄 Page
3
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2020 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Susanna Kline 20 Baldwin Road Technical development editor: Dennis Sellinger PO Box 761 cReview editor: Aleks Dragosavljevi´ Shelter Island, NY 11964 Production editor: Lori Weidert Copy editor: Andy Carroll Proofreader: Keri Hales Technical proofreader: George Onofrei Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617295942 Printed in the United States of America
📄 Page
4
iii contents preface ix acknowledgments xi about this book xii about the cover illustration xvi PART 1 MASTERING THE TYPESCRIPT SYNTAX.........................1 1 Getting familiar with TypeScript 3 1.1 Why program in TypeScript 4 1.2 Typical TypeScript workflows 7 1.3 Using the Typescript compiler 9 1.4 Getting familiar with Visual Studio Code 12 2 Basic and custom types 16 2.1 Declaring variables with types 17 Basic type annotations 17 ■ Types in function declarations 21 The union type 23
📄 Page
5
CONTENTSiv 2.2 Defining custom types 26 Using the type keyword 26 ■ Using classes as custom types 28 Using interfaces as custom types 30 ■ Structural vs. nominal type systems 32 ■ Unions of custom types 35 2.3 The any and unknown types, and user-defined type guards 37 2.4 A mini project 39 3 Object-oriented programming with classes and interfaces 41 3.1 Working with classes 42 Getting familiar with class inheritance 42 ■ Access modifiers public, private, protected 44 ■ Static variables and a singleton example 47 ■ The super() method and the super keyword 49 Abstract classes 51 ■ Method overloading 54 3.2 Working with interfaces 60 Enforcing the contract 60 ■ Extending interfaces 62 Programming to interfaces 64 4 Using enums and generics 69 4.1 Using enums 69 Numeric enums 70 ■ String enums 73 ■ Using const enums 75 4.2 Using generics 76 Understanding generics 77 ■ Creating your own generic types 82 Creating generic functions 86 ■ Enforcing the return type of higher-order functions 91 5 Decorators and advanced types 93 5.1 Decorators 94 Creating class decorators 96 ■ Creating method decorators 101 5.2 Mapped types 103 The Readonly mapped type 103 ■ Declaring your own mapped types 107 ■ Other built-in mapped types 108 5.3 Conditional types 111 The infer keyword 115 6 Tooling 118 6.1 Source maps 119 6.2 The TSLint linter 122
📄 Page
6
CONTENTS v 6.3 Bundling code with Webpack 125 Bundling JavaScript with Webpack 126 ■ Bundling TypeScript with Webpack 131 6.4 Using the Babel compiler 135 Using Babel with JavaScript 139 ■ Using Babel with TypeScript 141 ■ Using Babel with TypeScript and Webpack 143 6.5 Tools to watch 144 Introducing Deno 144 ■ Introducing ncc 146 7 Using TypeScript and JavaScript in the same project 150 7.1 Type definition files 151 Getting familiar with type definition files 151 ■ Type definition files and IDEs 153 ■ Shims and type definitions 156 ■ Creating your own type definition files 158 7.2 A sample TypeScript app that uses JavaScript libraries 159 7.3 Introducing TypeScript in your JavaScript project 167 PART 2 APPLYING TYPESCRIPT IN A BLOCKCHAIN APP ..........173 8 Developing your own blockchain app 175 8.1 Blockchain 101 176 Cryptographic hash functions 177 ■ What a block is made of 179 ■ What’s block mining 180 ■ A mini project with hash and nonce 183 8.2 Developing your first blockchain 185 The project’s structure 186 ■ Creating a primitive blockchain 189 ■ Creating a blockchain with proof of work 192 9 Developing a browser-based blockchain node 196 9.1 Running the blockchain web app 197 The project structure 197 ■ Deploying the app using npm scripts 200 ■ Working with the blockchain web app 201 9.2 The web client 203 9.3 Mining blocks 208 9.4 Using crypto APIs for hash generation 213
📄 Page
7
CONTENTSvi 9.5 The standalone blockchain client 216 9.6 Debugging TypeScript in the browser 219 10 Client-server communications using Node.js, TypeScript, and WebSockets 222 10.1 Resolving conflicts using the longest chain rule 223 10.2 Adding a server to the blockchain 226 10.3 The project structure 227 10.4 The project’s configuration files 228 Configuring the TypeScript compilation 228 ■ What’s in package.json 230 ■ Configuring nodemon 232 ■ Running the blockchain app 233 10.5 A brief introduction to WebSockets 239 Comparing HTTP and WebSocket protocols 240 ■ Pushing data from a Node server to a plain client 241 10.6 Reviewing notification workflows 245 Reviewing the server’s code 247 ■ Reviewing the client’s code 258 11 Developing Angular apps with TypeScript 269 11.1 Generating and running a new app with Angular CLI 270 11.2 Reviewing the generated app 273 11.3 Angular services and dependency injection 278 11.4 An app with ProductService injection 282 11.5 Programming to abstractions in TypeScript 285 11.6 Getting started with HTTP requests 287 11.7 Getting started with forms 290 11.8 Router basics 295 12 Developing the blockchain client in Angular 300 12.1 Launching the Angular blockchain app 301 12.2 Reviewing AppComponent 303 12.3 Reviewing TransactionFormComponent 307 12.4 Reviewing the BlockComponent 309 12.5 Reviewing services 311
📄 Page
8
CONTENTS vii 13 Developing React.js apps with TypeScript 315 13.1 Developing the simplest web page with React 316 13.2 Generating and running a new app with Create React App 319 13.3 Managing a component’s state 323 Adding state to a class-based component 324 ■ Using hooks to manage state in functional components 325 13.4 Developing a weather app 328 Adding a state hook to the App component 329 ■ Fetching data with the useEffect hook in the App component 332 ■ Using props 338 ■ How a child component can pass data to its parent 343 13.5 What’s Virtual DOM? 346 14 Developing a blockchain client in React.js 348 14.1 Starting the client and the messaging server 349 14.2 What changed in the lib directory 352 14.3 The smart App component 354 Adding a transaction 355 ■ Generating a new block 359 Explaining the useEffect() hooks 359 ■ Memoization with the useCallback() hook 361 14.4 The TransactionForm presentation component 365 14.5 The PendingTransactionsPanel presentation component 368 14.6 The BlocksPanel and BlockComponent presentation components 370 15 Developing Vue.js apps with TypeScript 374 15.1 Developing the simplest web page with Vue 375 15.2 Generating and running a new app with Vue CLI 378 15.3 Developing single-page apps with router support 385 Generating a new app with the Vue Router 387 ■ Displaying a list of products in the Home view 390 ■ Passing data with the Vue Router 397 16 Developing the blockchain client in Vue.js 402 16.1 Starting the client and the messaging server 403 16.2 The App component 406
📄 Page
9
CONTENTSviii 16.3 The TransactionForm presentation component 410 16.4 The PendingTransactionsPanel presentation component 415 16.5 The BlocksPanel and Block presentation components 416 appendix Modern JavaScript 423 index 459
📄 Page
10
ix preface This book is about the programming language TypeScript, which is one of the most loved languages, according to the Developer Survey on Stack Overflow (see https:// insights.stackoverflow.com/survey/2019). According to the latest issue of the reputa- ble ThoughtWork’s Technology Radar (http://mng.bz/Ze5P), “TypeScript is a carefully considered language and its consistently improving tools and IDE support continues to impress us. With a good repository of TypeScript-type definitions, we benefit from all the rich JavaScript libraries while gaining type safety.” We use TypeScript daily, and we like it a lot! We really like TypeScript for allowing us to focus on the main problem we’re solving and not on typos in an object’s prop- erty name. In TypeScript programs, the chances of getting runtime errors are substan- tially lower compared to code originally written in JavaScript. We also like that IDEs offer great TypeScript support and literally walk us through the maze of APIs from third-party libraries we use in our projects. TypeScript is great, but since it’s a compiled-to-JavaScript language, we also need to talk a bit about JavaScript. In May 1995, after 10 days of hard work, Brendan Eich cre- ated the JavaScript programming language. This scripting language didn’t need a compiler and was meant to be used in the Netscape Navigator web browser. No compilers were needed to deploy a JavaScript program in the browser. Adding a <script> tag with the JavaScript sources (or a reference to a file with sources) would instruct the browser to load and parse the code and execute it in the browser’s Java- Script engine. People enjoyed the simplicity of the language—there was no need to
📄 Page
11
PREFACEx declare the types of variables and no need to use any tools. You’d just write your code in a plain text editor and use it in a web page. When you first start learning JavaScript, you can see your first program running in two minutes. There’s nothing to install or configure, and there’s no need to compile the program, because JavaScript is an interpreted language. JavaScript is also a dynamically typed language, which gives additional freedom to software developers. There’s no need to declare an object’s properties up front, as the JavaScript engine will create the property at runtime if the object doesn’t already have it. Actually, there’s no way to declare the type of a variable in JavaScript. The Java- Script engine will guess the type based on the assigned value (for example, var x = 123 means that x is a number). If, later on, the script has an assignment x ="678", the type of x will automatically change from a number to a string. Did you really want to change the type of x or was that a mistake? You’ll know that only at runtime, as there’s no compiler to warn you about it. JavaScript is a very forgiving language, which is not a shortcoming if the codebase is small, and you’re the only person working on the project. Most likely, you’ll remember that x is supposed to be a number, and you don’t need any help with this. And, of course, you’ll work for your current employer forever, so the variable x is never forgotten. Over the years, JavaScript became super popular and the de facto standard program- ming language of the web. But 20 years ago, developers used JavaScript to display web pages with some interactive content; today we develop complex web apps that contain thousands of lines of code developed by teams of developers. Not everyone in your team remembers that x was supposed to be a number. To minimize the number of run- time errors, JavaScript developers write unit tests and perform code reviews. To be more productive, software developers get help from IDEs with autocomplete features, easy refactoring, and so on. But how can an IDE help you with refactoring if the language allows complete freedom in adding properties to objects and changing types on the fly? Web developers needed a better language, but replacing JavaScript with another one that would be supported by all the different browsers was not realistic. Instead, new compile-to-JavaScript languages were created. They were more tool-friendly, but the program still had to be converted to JavaScript before deployment so every browser could support it. TypeScript is one of these languages, and after reading this book, you’ll see what makes it stand out.
📄 Page
12
xi acknowledgments Yakov would like to thank his best friend Sammy for creating a warm and cozy envi- ronment while he was working on this book. Unfortunately, Sammy can’t talk, but like any dog, he loves all his family members more than they love themselves. Anton would like to thank the authors of and contributors to the open source proj- ects used in this book. Without the numerous hours they regularly dedicate to the projects, and their constant work growing and supporting communities, this book wouldn’t be possible. He’s also grateful to his family for being patient while he was working on the book. Special thanks go to multiple book reviewers who provided valuable feedback: Ahmad F Subahi, Alexandros Dallas, Brian Daley, Cameron Presley, Cameron Singe, Deniz Vehbi, Floris Bouchot, George Onofrei, George Thomas, Gerald James Stralko, Guy Langston, Jeff Smith, Justin Kahn, Kent R. Spillner, Kevin Orr, Lucas Pardue, Marko Letic, Matteo Battista, Paul Brown, Polina Keselman, Richard Tuttle, Srihari Sridharan, Tamara Forza, and Thomas Overby Hansen.
📄 Page
13
xii about this book Who should read this book This book is written for software engineers who want to become more productive developing web or standalone apps. Both authors are practitioners, and we wrote this book for practitioners. Not only do we explain the syntax of the language using basic code samples, but we also develop multiple apps that show how you can use Type- Script with popular libraries and frameworks. While working on this book, we ran workshops using the code samples from the book, giving us early feedback about the book’s content. We really hope that you’ll enjoy the process of learning TypeScript with this book. We expect readers to have a working knowledge of HTML, CSS, and JavaScript that use recent additions from ECMAScript specs. If you are only familiar with the ECMAScript 5 syntax, looking through the appendix first will make it easier to under- stand the code samples in the book—the appendix provides an introduction to mod- ern JavaScript. How this book is organized: A roadmap This book is divided into two parts. In part 1, we cover various syntax elements of TypeScript using small code snippets for illustration. In part 2, we apply TypeScript in several versions of a blockchain app. If your goal is to quickly learn TypeScript’s syntax and tooling, part 1 of this book is all you need. Chapter 1 will get you started with TypeScript development. You’ll compile and run very basic programs so you understand the workflow, from writing a program in
📄 Page
14
ABOUT THIS BOOK xiii TypeScript to compiling it into runnable JavaScript. We’ll also cover the benefits of programming in TypeScript versus JavaScript and introduce the Visual Studio Code editor. Chapter 2 explains how to declare variables and functions with types. You’ll learn how to declare type aliases with the type keyword and how to declare custom types with classes and interfaces. This will help you understand the difference between nominal and structural type systems. Chapter 3 explains how class inheritance works and when to use abstract classes. You’ll see how TypeScript interfaces can force a class to have methods with known sig- natures, without worrying about the implementation details. You’ll also learn what “programming to interfaces” means. Chapter 4 is dedicated to enums and generics. This chapter covers the benefits of using enums, the syntax for numeric and string enums, what generic types are for, and how to write classes, interfaces, and functions that support generics. Chapter 5 covers decorators and mapped and conditional types. It’s about advanced TypeScript types, and you should be familiar with the syntax of generics to understand the material in this chapter. Chapter 6 is about tooling. We explain the use of source maps and TSLinter (although TSLinter is being deprecated, many developers are still using it). Then we show you how to compile and bundle TypeScript apps with Webpack. You’ll also learn how and why to compile TypeScript with Babel. Chapter 7 teaches you to use JavaScript libraries in your TypeScript app. We start by explaining the role of type definition files, and then we present a small app that uses a JavaScript library in a TypeScript app. Finally, we go over the process of gradu- ally upgrading an existing JavaScript project to TypeScript. In part 2, we apply TypeScript in a blockchain app. You might be thinking to your- self, “None of the companies I’ve worked for are using blockchain technology, so why should I learn about blockchain when my goal is to master TypeScript?” We didn’t want our sample app to be yet another ToDo example, so we looked for a hot technology where you could apply the different TypeScript elements and techniques introduced in part 1. Seeing how TypeScript is used in a not-so-trivial app will make this content more practical, even if you’re not going to use blockchain technology in the near future. In this part of the book, you’ll develop several blockchain apps: a standalone app, a browser app, an Angular app, a React.js app, a Vue.js app. Feel free to read only those chapters that interest you, but make sure you read chapters 8 and 10 where the foundational concepts are introduced. Chapter 8 introduces the principles of blockchain apps. You’ll learn what the hash- ing functions are for, what block mining means, and why the proof of work is required to add a new block to a blockchain. After covering the blockchain basics, we present a project and explain the code that creates a basic blockchain app. Most chapters in part 2 have runnable blockchain projects with detailed explanations of how they were written and how to run them.
📄 Page
15
ABOUT THIS BOOKxiv Chapter 9 describes how to create a web client for a blockchain. This app will not use any web frameworks; we’ll use only HTML, CSS, and TypeScript. We’ll also create a small library for hash generation that can be used in both web and standalone cli- ents. You’ll also see how to debug your TypeScript code in the browser. Chapter 10 reviews the code of a blockchain app that uses a messaging server for communications between blockchain members. We create a Node.js and WebSocket server in TypeScript, and we’ll show you how the blockchain uses the longest chain rule to achieve consensus. You’ll find practical examples of using TypeScript inter- faces, abstract classes, access qualifiers, enums, and generics. Chapter 11 provides a brief introduction to developing web apps in Angular with TypeScript, and chapter 12 reviews the code of a blockchain web client developed using this framework. Chapter 13 offers a brief introduction to developing web apps in React.js with TypeScript, and chapter 14 reviews the code of a blockchain web client developed using React. Chapter 15 similarly introduces developing web apps in Vue.js with TypeScript, and chapter 16 reviews the blockchain web client developed with this Vue. About the code This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to high- light code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. Part 1 is about the syntax of the language, and most of the code samples are pub- lished online on the TypeScript Playground—an interactive tool that quickly checks the syntax of a TypeScript code snippet and compiles it into JavaScript. The links to these code snippets are provided in the book as needed. The second part of the book consists of multiple projects that use TypeScript to develop applications using popular libraries and frameworks (such as Angular, React.js, and Vue.js). The source code of these apps is located on GitHub at https:// github.com/yfain/getts. We thoroughly tested every app that comes with the book, but new versions of TypeScript and other libraries may be released, with breaking changes. If you’re get- ting an error while trying to run one of these projects, please open an issue on the book’s GitHub repository.
📄 Page
16
ABOUT THIS BOOK xv liveBook discussion forum Purchase of Typescript Quickly includes free access to a private web forum run by Man- ning Publications where you can make comments about the book, ask technical ques- tions, and receive help from the author and from other users. To access the forum, go to https://livebook.manning.com/#!/book/TypeScriptQuickly/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://live- book.manning.com/#!/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We sug- gest you try asking the author some challenging questions lest their interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print. About the authors Yakov Fain is a cofounder of two IT companies: Farata Systems and SuranceBay. He has authored and co-authored books such as Java Programming: 24-Hour Trainer, Angu- lar Development with TypeScript, Java Programming for Kids, and others. A Java Champion, he has taught multiple classes and workshops on web- and Java-related technologies and has presented at international conferences. Fain has written more than a thou- sand blog entries at yakovfain.com. His Twitter and Instagram handles are @yfain. He also publishes videos on YouTube. Anton Moiseev is a lead software developer at SuranceBay. He’s been developing enterprise applications for more than a decade with Java and .NET technologies. He has a solid background and a strong focus on web technologies, implementing best practices to make the frontend work seamlessly with the backend. He has taught a number of training sessions on AngularJS and Angular frameworks. He blogs occa- sionally at antonmoiseev.com, and his Twitter handle is @antonmoiseev.
📄 Page
17
xvi about the cover illustration The figure on the cover of TypeScript Quickly is captioned “Bourgeoise Florentine.” The illustration is taken from a collection of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757–1810), titled Costumes civils actuels de tous les peuples connus, published in France in 1788. Each illustration is finely drawn and col- ored by hand. The rich variety of Grasset de Saint-Sauveur’s collection reminds us viv- idly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress. The way we dress has changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different conti- nents, let alone different towns, regions, or countries. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technological life. At a time when it is hard to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Grasset de Saint-Sauveur’s pictures.
📄 Page
18
Part 1 Mastering the TypeScript syntax Part 1 starts with explaining the benefits of TypeScript compared to Java- Script. Then, we’ll cover various syntax elements of TypeScript using small code snippets for illustration. You’ll see how to use built-in and declare custom types. We’ll introduce the use of classes and interfaces as well as generics, enums, deco- rators, mapped and conditional types. You’ll learn the tooling used by Type- Script developers (such as compilers, linters, debuggers, and bundlers). Finally, we’ll show you how to use the TypeScript and JavaScript code in the same app. For those of you who like learning by watching videos, Yakov Fain has pub- lished a number of videos (see http://mng.bz/m4M8) that illustrate the materi- als from Part 1 of this book. If your goal is to quickly learn the TypeScript’s syntax and tooling, Part 1 of this book is all you need.
📄 Page
19
(This page has no text content)
📄 Page
20
3 Getting familiar with TypeScript The goal of this chapter is to get you started with TypeScript development. We’ll start by paying respect to JavaScript, and then we’ll share our own opinion on why you should be programming in TypeScript. To round out this chapter, we’ll com- pile and run a very basic program so you can follow the workflow from writing a program in TypeScript to compiling it into runnable JavaScript. If you’re a seasoned JavaScript developer you’d need a good reason to switch to TypeScript, which would have to be compiled into JavaScript before deployment anyway. If you’re a backend developer planning to learn the frontend ecosystem, you’d also need a reason for learning any programming language other than Java- Script, so let’s start with the reasoning. This chapter covers The benefits of programming in TypeScript over JavaScript How to compile the TypeScript code into JavaScript How to work with the Visual Studio Code editor