📄 Page
1
(This page has no text content)
📄 Page
2
TypeScript for Beginners
📄 Page
3
(This page has no text content)
📄 Page
4
TypeScript for Beginners The Ultimate Guide Sufyan bin Uzayr
📄 Page
5
First edition published 2022 by CRC Press 6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742 and by CRC Press 2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN CRC Press is an imprint of Taylor & Francis Group, LLC © 2022 Sufyan bin Uzayr Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may rectify in any future reprint. Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission from the publishers. For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not available on CCC please contact mpkbookspermissions@tandf. co.uk Trademark Notice: Product or corporate names may be trademarks or registered trademarks and are used only for identification and explanation without intent to infringe. ISBN: 9781032067582 (hbk) ISBN: 9781032067575 (pbk) ISBN: 9781003203728 (ebk) DOI: 10.1201/9781003203728 Typeset in Minion Pro by KnowledgeWorks Global Ltd.
📄 Page
6
v Contents Acknowledgments, xiii About the Author, xv Chapter 1 ◾ TypeScript: Introduction to TypeScript 1 WHAT IS TS? 1 A BRIEF HISTORY OF TS 1 WHY SHOULD YOU CHOOSE TS? 2 How Does TS Help Developers Code Easier? 3 How Exactly Does TS Improve JS? 3 TS AS COMPARED TO JS 5 What Is JS? 5 TS Strengths 5 Syntactic Sugar 6 TS STRUCTURE 7 Basic TS Types 8 Boolean 9 Number 9 String 9 Array 10 Tuple 10 Tuples Deconstruction 11 Optional Tuple Elements 12 Enum 13
📄 Page
7
vi ◾ Contents String Enums 15 Any 15 Void 16 Null and Undefined 17 Never 17 Symbol 18 Type Assertions 18 The Let Keyword 19 TS Compiler 19 Variable Declarations 20 var Declarations 20 Scoping 21 Block Viewport 22 Re-declaring and Escaping 23 Closure of Variables with Block Scope Viewability 25 Constant Declarations 26 Let or Const? 27 Destructuring 27 Destructuring an Object 28 Renaming Properties 28 Default Values 28 Declaring Functions 29 Interfaces 30 Extending Interfaces 32 Indexed Types 32 Interface Implementation 32 Discriminated Union Types 33 Working with Interfaces 35 Optional Properties 36 Read-Only Properties 37
📄 Page
8
Contents ◾ vii Checks for Extra Properties 38 Functional Types 40 Indexed Types 41 INTEGRATED DEVELOPMENT ENVIRONMENTS 43 Node-Based Compilation 43 Creating a tsconfig.json File 44 Chapter 2 ◾ Key Concepts of TS 47 CLASSES 47 Inheritance 48 Interface Inheritance 49 Class Inheritance 50 Access Modifiers 51 Public by Default 51 Private Modifier 52 Protected Modifier 53 Readonly Modifier 55 Type Iterator Modifier 55 Parameter Properties 58 Accessors (Getters/Setters) 58 Static Properties 59 Abstract Classes 60 Constructors 61 Using a Class as an Interface 63 FUNCTIONS 64 Types of Functions 64 Adding Types to a Function 64 Inferring Types 65 Best General Type 66 Context Type 67
📄 Page
9
viii ◾ Contents Anonymous Functions 68 Type Compatibility 69 Optional Parameters and Default Parameters 70 Rest Parameters 73 this Keyword 74 Keyword “this” and Arrow Functions 75 this Parameters 77 this Parameters for Callback Functions 78 Overloads 80 GENERICS 83 Exploring the World of Generics 83 Working with Generalized Type Variables 84 Generalized Types 86 Generalized Classes 88 Limitations of Generalizations 88 Using Generic Parameters in Generalization Constraints 89 Using Class Types in Generalizations 90 new Keyword 91 ENUMS 92 Constant Enums 93 Declare Enums 95 SYMBOLS 96 Predefined Characters 97 Chapter 3 ◾ Modules and Namespaces 99 WHAT IS NAMESPACE? 99 WHAT IS MODULE? 100 Export 101 Export Validation 102 Reexport 102 Import 103 Importing a Single Exported Item 103
📄 Page
10
Contents ◾ ix Importing the Entire Module into a Single Variable, and Using It to Access the Exported Module Elements 103 Importing a Module for the Sake of “Side Effects” 103 Default Export 103 Generating Code for Modules 105 Optional Module Loading and Its Other Advanced Scenarios 108 Working with Other JavaScript Libraries 110 EXTERNAL MODULES 110 Abbreviated External Module Declaration Entry 111 Module Declarations Using Wildcard Characters 111 UMD MODULES 112 STRUCTURING MODULES 112 Export as Close to the Top Level as Possible 112 If You Export Only One Class or One Function, Use Export Default 112 If You Are Exporting Multiple Objects, Put Them on the Top Level 113 Explicitly Define the Imported Names 113 Use the Namespace Import Template When Importing a Large Number of Items 113 Do Not Use Namespaces in Modules 114 Risk Indicators 114 Loading Modules 115 Module Resolution 117 Relative and Nonrelative Module Imports 117 Module Resolution Strategies 118 How Does Node.js Resolve Modules? 119 Additional Flags of the Module Resolution System 120 Base URL 121 Path Mapping 121 Virtual Directories with rootDirs 123
📄 Page
11
x ◾ Contents Tracking Module Resolution 124 What to Look for in the Trace? 126 Chapter 4 ◾ TS Runtime 127 WHAT IS RUNTIME? 127 NODE.JS 127 WHY TYPESCRIPT IS HERE TOO? 128 Why Node.js? 128 WHAT IS DENO? 128 Main Features of Deno 129 Safety 129 Module System 129 Installation of Deno 130 Installation in Windows 130 Internal Part 131 Safety 132 Strict: True by Default 133 Deno Modules 133 Deno.core 134 Deno Standard Modules 134 Deno X 134 Package Manager 134 Lock File 135 Web Standards 135 WASM, RUST, Plugins 136 Debugging 136 Testing 137 Integration Testing 137 Compiler API 137 dev_server 138 INSTALLING AND COMPILING THE TS 139 Installation via NPM 139
📄 Page
12
Contents ◾ xi Installing as a Visual Studio Plugin 140 Compiling an App 140 MERGING DECLARATIONS 142 Basic Concepts 142 Merging Interfaces 142 Merging Namespaces 144 Merging Namespaces with Classes, Functions, and Enumerations 145 Merging Namespaces with Classes 145 Prohibited Merges 146 Chapter 5 ◾ TypeScript Architecture 151 WHAT IS AN APPLICATION ARCHITECTURE? 151 WHY DO WE NEED ARCHITECTURE? 151 SINGLE-PAGE APPLICATION 152 MULTI-PAGE ARCHITECTURE 152 CREATING AN APPLICATION IN TYPESCRIPT 153 MAKING AN APP 154 COMPILATION: WATCH MODE 155 MV* ARCHITECTURE 155 MVC (MODEL VIEW CONTROLLER) 155 Model 156 View 156 Controller 157 MVC FRAMEWORKS 159 BACKBONE 160 AURELIA 161 ANGULAR 162 REACT 164 Webpack Configuration 166 TEST-DRIVEN DEVELOPMENT 166
📄 Page
13
xii ◾ Contents MODULE, INTEGRATION, AND ACCEPTANCE TESTINGS 168 Module Testings 168 Integration Testings 169 Acceptance Testings 169 REFACTORING 170 TYPESCRIPT 4.2 RELEASE 170 SUPPORT FOR REST ELEMENTS IN THE FIRST AND INTERMEDIATE PARAMETERS OF TUPLES OF TYPES 170 SAVING-TYPE ALIASES 171 THE ABSTRACT MODIFIER IN CONSTRUCTOR SIGNATURES 171 Strict Checks for the In Statement 172 UNUSED VARIABLES DURING ARRAY DESTRUCTURIZATION 172 TYPE ARGUMENTS 172 Future Plans 173 Chapter 6 ◾ Appraisal 175 APPENDIX, 177 INDEX, 181
📄 Page
14
xiii Acknowledgments There are many people who deserve to be on this page, for this book would not have come into existence without their support. That said, some names deserve a special mention, and I am genuinely grateful to: • My parents, for everything they have done for me • My siblings, for helping with things back home • The Parakozm team, especially Aruzhan Nuraly and Madina Karybzhanova, for offering great amounts of help and assistance during the book-writing process • The CRC team, especially Sean Connelly and Jessica Vega, for ensur- ing that this book’s content, layout, formatting, and everything else remains perfect throughout • Reviewers of this book, for going through the manuscript and pro- viding their insight and feedback • Typesetters, cover designers, printers, and everyone else, for their part in the development of this book • All the folks associated with Zeba Academy, either directly or indi- rectly, for their help and support • The programming community in general, and the web development community in particular, for all their hard work and efforts Sufyan bin Uzayr
📄 Page
15
(This page has no text content)
📄 Page
16
xv About the Author Sufyan bin Uzayr is a writer, coder, and entrepreneur with more than a decade of experience in the industry. He has authored several books in the past, pertaining to a diverse range of topics, ranging from history to computers/IT. Sufyan is the Director of Parakozm, a multinational IT company spe- cializing in EdTech solutions. He also runs Zeba Academy, an online learning and teaching vertical with a focus on STEM fields. He special- izes in a wide variety of technologies, such as JavaScript, Dart, WordPress, Drupal, Linux, and Python, and he holds multiple degrees, including ones in management, IT, literature, and political science. Sufyan is a digital nomad, dividing his time between four countries. He has lived and taught in universities and educational institutions around the globe. He takes a keen interest in technology, politics, literature, his- tory, and sports, and in his spare time, he enjoys teaching coding and English to young students. Learn more at sufyanism.com.
📄 Page
17
(This page has no text content)
📄 Page
18
1DOI: 10.1201/9781003203728-1 C h a p t e r 1 TypeScript Introduction to TypeScript TypeScript (TS) is a typed extended set of JavaScript (JS) that compiles to plain JS. As an analogy, if JS was CSS, then TS would be SCSS. All valid JS code you write is also valid TS code. However, by using TS, you get to use static typing and the latest features that compile into simple JS that is supported by all browsers. TS aims to solve the JS scaling prob- lem, and it works pretty well. In this book, you’ll start by reading about the various features of TS and why learning it is a good idea. The rest of this book will focus on install- ing and compiling TS, along with some popular text editors that offer you support for TS syntax and other important features. WHAT IS TS? TS is a kind of updated version of the JS language. It can run on Node.js or any web browser that supports ECMAScript 3 or higher. TS is a stati- cally compiled language that provides optional static typing, classes, and an interface. It allows you to write simple and clean JS code. So, adopting TS can help you create more easily deployable and more reliable software. A BRIEF HISTORY OF TS TS development began in late 2012. Although it originated in Microsoft, and its actual creator is the programmer Anders Hejlsberg, also known as
📄 Page
19
2 ◾ TypeScript for Beginners the creator of such languages as Delphi and C#, this project immediately began to develop as an OpenSource. And from the very beginning, the new language began to spread rapidly due to its flexibility and performance. A lot of projects that were written in JS were transferred to TS. The popular- ity and relevance of the ideas of the new language has led to the fact that a number of these ideas will later become part of the new JS standard. And the new version of one of the most popular frameworks for web – Angular 2/4/5/6 is completely written in TS jointly by Microsoft and Google. WHY SHOULD YOU CHOOSE TS? However, it would seem that there is no need for another programming language for the client side in the web environment, if traditional JS, which is used on almost every site, which is owned by many developers and whose support in the programming community is quite high, also copes with all the same work. But TS is not just a new JS. First, it should be noted that TS is a strongly typed and compiled lan- guage, which may be closer to programmers of Java, C#, and other strongly typed languages, although the output of the compiler creates the same JS, which is then executed by the browser. However, strong typing reduces the number of potential errors that could occur when developing in JS. Second, TS implements many of the concepts that are common to object-oriented languages, such as inheritance, polymorphism, encapsu- lation, access modifiers, and so on. Third, the potential of TS makes it faster and easier to write large com- plex programs, and therefore easier to maintain, develop, scale, and test them than in standard JS. Fourth, TS develops as an opensource project and, like many projects, is hosted on GitHub. Repository address – https://github.com/Microsoft/ TypeScript. In addition, it is cross-platform, which means that we can use both Windows and macOS or Linux for development. At the same time, TS is a superset of JS, which means that any JS pro- gram is a TS program. In TS, you can use all the constructs that are used in JS – the same operators, conditional, cyclic constructs. Moreover, the TS code is compiled in JS. Ultimately, TS is just a tool that is designed to make application development easier. Although this language does not provide additional functionality in the runtime, it offers a number of features that help developers write more reliable and easier-to-maintain code than in the case of pure JS.
📄 Page
20
TypeScript ◾ 3 How Does TS Help Developers Code Easier? As its name suggests, it adds a type system to JS. If in JS the type of a variable is assigned dynamically, then in TS we have to predefine its type immediately at the time of declaration. If we are talking about JS, then you can first assign an integer value to a variable, and then reassign it to a string value. let jsVar = 0; jsVar = "js"; In the case of TS, you can restrict this behavior by declaring the type for the variable explicitly. As a result, if you try, for example, to assign a string to a variable of type number, an error will occur. let tsVar: number = 0; tsVar = "ts"; //error In fact, this is what distinguishes TS from JS. It uses types, which allows us to avoid stupid errors in the code. How Exactly Does TS Improve JS? The lack of typing cannot be called a disadvantage of JS, but it gives pro- grammers too much freedom, which inevitably leads to writing code with errors. let aNumber = 123;aNumber = { name: "Sufyan", age: 29 } In the JS example above, nothing prevents the developer from presenting the object via the aNumber variable. This approach, although it will not cause the program to crash, will completely eliminate the possibility of self-documenting the code at the expense of variable names. TS easily solves this problem by defining the type of a variable when it is declared, without further assigning it to a value of another type. let aNumber: number = 123;