TypeScript High Performance 1st Edition Ajinkya Kher pdf download
TypeScript High Performance 1st Edition Ajinkya Kher pdf download
https://ebookname.com/product/typescript-high-performance-1st-
edition-ajinkya-kher/
https://ebookname.com/product/nginx-high-performance-1st-edition-
rahul-sharma/
https://ebookname.com/product/high-performance-pigments-2nd-
edition-faulkner/
https://ebookname.com/product/high-performance-loudspeakers-
sixth-edition-martin-colloms/
https://ebookname.com/product/aashto-lrfd-bridge-design-
specifications-customary-u-s-units-with-2012-and-2013-interim-
revisions-and-2012-errata-6th-edition-edition-sam-zhang/
Rule of Two Star Wars Darth Bane Book 2 Drew Karpyshyn
https://ebookname.com/product/rule-of-two-star-wars-darth-bane-
book-2-drew-karpyshyn/
https://ebookname.com/product/cliffs-ap-english-language-and-
composition-2nd-edition-barbara-v-swovelin/
https://ebookname.com/product/fundamentals-of-engineering-
thermodynamics-5th-edition-michael-j-moran/
https://ebookname.com/product/careerjournal-com-resume-guide-
for-100-000-plus-executive-jobs-1st-edition-william-e-montag/
https://ebookname.com/product/health-issues-injuries-and-
diseases-1st-edition-tsisana-shartava/
Electric Power Distribution Reliability 1st Edition
Richard E. Brown
https://ebookname.com/product/electric-power-distribution-
reliability-1st-edition-richard-e-brown/
TypeScript High Performance
Ajinkya Kher
BIRMINGHAM - MUMBAI
TypeScript High Performance
Copyright © 2017 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, and its
dealers and distributors will be held liable for any damages caused or alleged to be 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.
ISBN 978-1-78528-864-7
www.packtpub.com
Credits
I am impressed by how much ground Ajinkya has covered in this book. Given his solid
background in full-stack software development, experience working with real-time
systems, and the desire to learn and grow along the way, the polished outcome in the form
of this book is not surprising. Ajinkya has truly brought his knowledge and insights to the
readers in an accessible manner and has let them in on the winning secrets that he has
leveraged in both professional settings and while triumphing in multiple Hackathons.
As a passionate technologist, fueled engineer, and creative problem solver, I have been a
witness and part of this evolution. I started using JavaScript in 2001 and have thoroughly
enjoyed the evolution since then. I enjoy the quirks of the language and the tiny things I’ve
spent hours trying to debug. I used to code in Notepad and would spend the proverbial 8
hours searching for a misspelled variable and massaging the bruises on my forehead from
the wall. I enjoy listening to everyone’s unique story about how they discovered that the
parseInt() function defines and documents two parameters, with the second being the radix
and probably the most frustrating parameter as it does not default to the expected value of
10.
We all have those unique yet similar stories. With TypeScript, we will save our children
from those headaches and hopefully reduce their chronic traumatic encephalopathy from
continuously beating their head against your basement wall. I have dabbled with
technologies on personal projects and I have worked for some of the biggest companies in
the world, including Microsoft, Siemens, Goldman Sachs, Deloitte, AT&T, and Coca-Cola.
With that experience, I hope that some of that can be shared with you as a reader of this
book.
If you are just beginning to venture into JavaScript or TypeScript, or if you’re a seasoned
veteran like me, you have something to gain from these pages. In my years of development
and consulting, I have never seen someone as passionate about learning tooling and
languages as Ajinkya. I worked with him when he first ventured into frontend development
with AngularJS.
The evolving world can be a scary place for most developers. This book has been designed
and is intended to allow you to smoothly transition from JavaScript to TypeScript, which is
why I highly recommend every JavaScript and TypeScript developer reads it cover to cover.
I recommend you read each section with an open mind and ask yourself questions or
consider reaching out to and engaging in forums, the publishing company, or industry
experts.
Congratulations on taking the first step toward the future of JavaScript, and smile while
you read this book!
Brian O’Connor
He loves getting his hands dirty with the latest and the greatest technologies out there. In
his free time, you can find him winning Hackathons, building mobile applications, and
lifting weights. He has been playing tennis for more than a decade and has been an ardent
fan of cricket and Sachin Tendulkar since childhood, his weekends are thus often spent
playing these two sports. He also likes to practice and read about spirituality and
philosophy whenever he can.
Check out his latest podcast Building Modern Web Applications using
React/Redux/Angular2/RxJs on YouTube and you can also follow him on LinkedIn.
Acknowlegement
I would like to express my gratitude to several people who have helped me through the
journey of this book. I would like to begin with my friends at Packt Publishing–-Sonali,
Kinnari, Vibhuti, and Zeeyan, who were of great help right from laying out the scope of the
book to offering comments, proofreading, and editing the chapters, all of which, I’m sure,
resulted in enhancing the quality of the book.
I would like to thank Brian and Maria for their generous contributions to this book. Both
Brian and Maria helped proofread the book and offered great feedback and encouragement.
I would like to specifically thank Brian for his invaluable contributions to Chapter 8, Build
and Development Strategies for Large-Scale Projects of this book.
I would like to thank Raji, who has constantly encouraged me to keep going and complete
this book. I would also like to thank my friends at work who encouraged me in the writing
process.
I would like to thank my family–-my mom, my dad, and my sister, Anushka, for their
invaluable and sincere feedback, encouragement, and most importantly, their patience
throughout the process. My parents were on a vacation here in Seattle as I was working
toward the completion of this book. They were very cheerful and supportive despite all the
time it took me away from them. This book wouldn’t have been complete without their
support.
Lastly, I would like to thank everyone who has helped shape me over the years and put me
in a position to share my insights and experience with you all in the form of this book.
About the Reviewer
Andrew Leith Macrae first cut his programming teeth on an Apple IIe, poking bytes into
the RAM. Over the years, he has developed interactive applications with Hypercard,
Director, Flash, and more recently, Adobe AIR for mobile. He has also worked with HTML
since there was HTML to work with and is currently working as a senior frontend
developer at The Learning Channel (www.tsc.ca), using Angular 4 with Typescript.
He is convinced that TypeScript is the future of JavaScript, bringing the structure and
discipline of strongly typed object-oriented language to facilitate efficient, intentional
coding for the development of large-scale applications for the Web.
You can find out more about Andrew or contact him at www.adventmedia.net.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.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.PacktPub.com and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at service@packtpub.com for more details.
At www.PacktPub.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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial
process. To help us improve, please leave us an honest review on this book's Amazon page
at https://www.amazon.com/dp/1785288644.
If you'd like to join our team of regular reviewers, you can e-mail us at
customerreviews@packtpub.com. We award our regular reviewers with free eBooks and
videos in exchange for their valuable feedback. Help us be relentless in improving our
products!
I dedicate this book to my mom, who is my first teacher, friend, and mentor. She taught me the
alphabet as a child, and she's still the first one to update me on the latest technological innovations.
She has dedicated her life towards my all-round growth and her contributions to my life are
incalculable.
Table of Contents
Preface 1
Chapter 1: Efficient Implementation of Basic Data Structures and
Algorithms 7
Strings 8
String concatenation 9
String replacement 12
Classes and interfaces 15
Loops and conditions 20
Arrays and sorting 26
Operators 30
Summary 33
Chapter 2: Variable Declarations, Namespaces, and Modules 34
Variable declarations 34
The var declarations 36
The let declarations 39
The const declarations 41
Namespaces and modules 41
Modules 45
Summary 48
Chapter 3: Efficient Usage of Advanced Language Constructs 49
Arrow functions 50
Mixins 55
Declaration merging 59
Triple-slash directives 64
Answers to declaration merging questions 67
Summary 71
Chapter 4: Asynchronous Programming and Responsive UI 72
Fundamentals of asynchronous programming and event loop 74
Synchronous data fetch 75
Asynchronous data fetch 76
Event loop 77
Callbacks 87
Callback Hell 93
Promises 95
Async and await 103
Summary 112
Chapter 5: Writing Quality Code 113
Unit tests 114
Static code analysis with TSLint 129
Setting up TSLint for your project 130
Editing default rules 136
Extending TSLint rules 138
TSLint VSCode Extension 139
Summary 142
Chapter 6: Efficient Resource Loading - Critical Rendering Path 143
Resource delivery across the internet 144
Optimizing the critical rendering path 148
Optimization 1 - render blocking CSS 152
Optimization 2 - render blocking JS 154
Non-blocking UI 157
Massive data downloads 157
Massive data uploads 161
Summary 162
Chapter 7: Profile Deployed JS with Developer Tools and Fiddler 163
Chrome Developer Tools 164
Memory profiling 164
Latency and computation time profiling 169
The Network tab 174
Fiddler 180
Summary 188
Chapter 8: Build and Deployment Strategies for Large-Scale Projects 189
Building locally 190
Grunt 190
Gulp 191
MSBuild 192
Continuous integration (CI) 193
The process 194
Jenkins 196
Bamboo 196
Continuous delivery (CD) 196
Chef 198
[]
Puppet 198
Containerization 198
Docker 199
Serverless applications 199
Testing 199
Summary 200
Index 201
[]
Preface
Over the last two decades, JavaScript has grown from enabling developers to perform
simple interactions with in-browser HTML to being the core of enterprise applications, both
frontend and backend. This success has become more apparent with the advent and
creations of NodeJS, Cordova, Ionic, and serverless frameworks, all of which have adopted
and support TypeScript. This growth, coupled with the ever-increasing demand for
complex and performant JavaScript, has fueled the need for stricter typing, structures, and
code decoupling.
With this evolution, it is necessary for learning to take place for newbies and gurus alike.
This book has been designed to walk through various topics of the language, building into
meaningful constructs to help you, as a TypeScript developer, build scalable, efficient, and
maintainable applications from the first line of code. We start by walking you through
language structure and terminology, continue through optimizing your code to load
quickly and fine-tune performance, and wrap up with a discussion on building and
deploying applications for large-scale and enterprise applications.
TypeScript is here to stay and will be looked back upon as the next iteration of JavaScript
just as its predecessors, such as Prototype, jQuery, Dojo, and Mootools, were. This book will
walk you through the language and will explain how to write efficient enterprise
TypeScript to scale.
Chapter 2, Variable Declarations, Namespaces, and Modules, describes the distinction and
correct usage of variable declarations. It also describes code organization strategies, namely
leveraging namespaces and modules.
Chapter 3, Efficient Usage of Advanced Language Constructs, covers several different language
constructs in TypeScript. It explains how to use them, the scenarios in which to use each
construct, and their efficient usage.
Chapter 4, Asynchronous Programming and Responsive UI, is a deep dive into the world of
asynchronous programming. We walk you through the massive performance hits your
application can take if not built correctly, and we discuss strategies and tips for efficient
coding.
Chapter 6, Efficient Resource Loading - Critical Rendering Path, introduces the critical
rendering path and the steps involved in the process of loading a web application. We
discuss strategies for quick and non-blocking resource loading to produce a highly
responsive and performant application load.
Chapter 7, Profile Deployed JS with Developer Tools and Fiddler, introduces the concept of
profiling and the tools available. We compare the performance results of quality code
written with the help of TSLint and compare it to poorly written TypeScript code.
[2]
Preface
Basic knowledge of TypeScript and some experience using JavaScript are prerequisites for
this book.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds
of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Since the
text variable was not previously defined, the log output will now display a compilation
error." A block of code is set as follows:
// const tests
function constTest(): () => number {
const x: number = 16;
x = 4; // Left-hand side of assignment expression cannot be
a constant
return function innerFunction(): number {
x++; // the operand of an increment or decrement operator
[3]
Preface
cannot be a constant
return x;
}
}
When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
New terms and important words are shown in bold. Words that you see on the screen, for
example, in menus or dialog boxes, appear in the text like this: "Let's take a look at the
Network tab of the Developer Tools."
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book-what you liked or disliked. Reader feedback is important for us as it helps us develop
titles that you will really get the most out of. To send us general feedback, simply e-mail
feedback@packtpub.com, and mention the book's title in the subject of your message. If
there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.
[4]
Preface
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
[5]
Preface
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-
we would be grateful if you could report this to us. By doing so, you can save other readers
from frustration and help us improve subsequent versions of this book. If you find any
errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting
your book, clicking on the Errata Submission Form link, and entering the details of your
errata. Once your errata are verified, your submission will be accepted and the errata will
be uploaded to our website or added to any list of existing errata under the Errata section of
that title. To view the previously submitted errata, go to
https://www.packtpub.com/books/content/support and enter the name of the book in the
search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come
across any illegal copies of our works in any form on the Internet, please provide us with
the location address or website name immediately so that we can pursue a remedy. Please
contact us at copyright@packtpub.com with a link to the suspected pirated material. We
appreciate your help in protecting our authors and our ability to bring you valuable
content.
Questions
If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.
[6]
Efficient Implementation of
1
Basic Data Structures and
Algorithms
One of the most important things to achieve optimal performance with any language is to
understand the correct usage of the data types and the constructs it offers. If leveraged
optimally, these features can help in producing a robust and high performance application,
but if leveraged in a non-optimal fashion, the same features can adversely impact the
overall performance and usability of the end product.
Let's take a look at the performance impact with the help of the following basic constructs,
operations, and data structures:
Strings
Let's start by taking a look at strings. In TypeScript, you can create a string in one of the
following ways:
var test1: string = 'test string';
For all practical purposes, you would almost always use the first way to work with strings.
The only difference between the two is that string is a literal type and a preferred way to
declare strings in TypeScript. String is an object type, which is essentially a wrapper object
around the string. From a performance standpoint, literal types tend to perform better than
object types. We can confirm this by running a simple code snippet as mentioned in the
following code snippet:
function createString_1(): string {
return `Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry''s
standard dummy text ever since the 1500s, when an unknown
printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also
the leap into electronic typesetting, remaining essentially
unchanged.It was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages, and more
recently with desktop publishing software like Aldus PageMaker
including versions of Lorem Ipsum.`;
}
[8]
Efficient Implementation of Basic Data Structures and Algorithms
time2 = Date.now();
console.log('Time difference (createString_2): ', time2 - time1);
The preceding code snippet creates a long string (the famous filler text mostly used as a
placeholder on visual web elements) using the preceding described two ways.
Now, let's take a look at the results of executing the preceding code snippet:
As you can see from the results, the literal type string does behave slightly better. The
creation of the string, however, is not the most impacting operation that would affect your
application. Let's take a look at some classic string manipulation operations.
String concatenation
Let's start with string concatenation. Take a look at the following code snippet:
function createString(): string {
return `Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry''s
[9]
Another Random Document on
Scribd Without Any Related Topics
back
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com