39,59 €
Exploit the features of TypeScript to easily create your very own web applications
TypeScript is an open source and cross-platform statically typed superset of JavaScript that compiles to plain JavaScript and runs in any browser or host.
This book is a step-by-step guide that will take you through the use and benefits of TypeScript with the help of practical examples. You will start off by understanding the basics as well as the new features of TypeScript 2.x. Then, you will learn how to work with functions and asynchronous programming APIs. You will continue by learning how to resolve runtime issues and how to implement TypeScript applications using the Object-oriented programming (OOP) and functional programming (FP) paradigms. Later, you will automate your development workflow with the help of tools such as Webpack. Towards the end of this book, you will delve into some real-world scenarios by implementing some full-stack TypeScript applications with Node.js, React and Angular as well as how to optimize and test them. Finally, you will be introduced to the internal APIs of the TypeScript compiler, and you will learn how to create custom code analysis tools.
If you are a developer aiming to learn TypeScript to build attractive web applications, this book is for you. No prior knowledge of TypeScript is required. However, a basic understanding of JavaScript would be an added advantage.
Remo H. Jansen is originally from Seville, Spain, but he currently lives in Dublin, Ireland, where he works as a web engineer at Stellwagen Technology and as a part-time lecturer at CCT College Dublin. Remo is a Microsoft MVP and an active member of the TS community. He organizes the Dublin TypeScript and Dublin OSS meetups, writes a blog, and maintains InversifyJS on GitHub.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 566
Veröffentlichungsjahr: 2018
Copyright © 2018 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: Merint MathewAcquisition Editor: Denim PintoContent Development Editor: Nikhil BorkarTechnical Editor: Madhunikita Sunil ChindarkarCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Tania DuttaProduction Coordinator: Arvindkumar Gupta
First published: September 2015 Second edition: April 2018
Production reference: 1270418
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78839-147-4
www.packtpub.com
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.
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
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 [email protected] 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.
Remo H. Jansen is originally from Seville, Spain, but he currently lives in Dublin, Ireland, where he works as a web engineer at Stellwagen Technology and as a part-time lecturer at CCT College Dublin.
Remo is a Microsoft MVP and an active member of the TS community. He organizes the Dublin TypeScript and Dublin OSS meetups, writes a blog, and maintains InversifyJS on GitHub.
Alejandro Lora Gómez is a software developer residing in Seville, Spain. He is an instructor at Udemy, where he teaches his best-selling courses on Android and Kotlin to over 25K students. Alejandro has a keen interest in web development with Angular and has been working with Angular for several years in multiple contexts (consulting, start-ups, and contracting) and countries (Spain, Ireland, and France), which has added professional value and experience to his career. Nowadays, he works remotely for a multinational corporation based in the USA as an Angular developer.
Carlos Landeras has been a Software Engineer for the past 10 years, being focused on .NET platform and JavaScript development for web solutions. He has been awarded the Microsoft MVP in Visual Studio and development technologies and has a large number of contributions as a speaker in different conferences and user groups. He works at Plain Concepts, a Microsoft Partner Company that provides innovative and engaging custom solutions. Plain Concepts is specialized in web, apps, ALM, Cloud, VR and AR, AI, and DevOps.
Andrew Leith Macrae first cut his programming teeth on an Apple IIe poking bytes into RAM. Over the years he has developed interactive applications with Hypercard, Director, Flash and HTML. He is currently a frontend developer at Arithmos. Andrew is convinced that TypeScript is the future, bringing the structure and discipline of strongly-typed object-oriented language to the web.
David Sherret is the author of ts-simple-ast. He is a software developer in the health-care industry, currently working on surgical planning and navigation software for neurosurgery at Synaptive Medical in Toronto, Canada. In the past, he has worked on several projects, including a project that supported the logistics behind specialty pharmaceuticals and technology for reducing health insurance fraud.
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.
Title Page
Copyright and Credits
Learning TypeScript 2.x Second Edition
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
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
Introducing TypeScript
The TypeScript architecture
Design goals
TypeScript components
TypeScript language features
Types
Type inference and optional static type annotations
Variables, basic types, and operators
Variable scope (var, let, and const)
Arithmetic operators
Comparison operators
Logical operators
Bitwise operators
Assignment operators
Spread operator
Flow control statements
The single-selection structure (if)
The double-selection structure (if...else)
The inline ternary operator (?)
The multiple-selection structure (switch)
The expression is tested at the top of the loop (while)
The expression is tested at the bottom of the loop (do...while)
Iterate on each object's properties (for...in)
Iterate values in an iterable (for...of)
Counter-controlled repetition (for)
Functions
Classes
Interfaces
Namespaces
Putting everything together
Summary
Working with Types
The TypeScript type system's characteristics
The line between TypeScript and JavaScript
Type inference
Optional static type annotations
Structural type system
Core features of the TypeScript type system
Union types
Type aliases
Intersection types
Non-nullable types
The --strict mode
The typeof operator
Type guards
Custom type guards
Control flow analysis
Literal types
Discriminated unions
The never type
Enumerations
Object literals
Weak types
The keyof operator
Index signature
Local types
Type casting
Advanced features of the TypeScript type system
Generic types
Generic constraints
Mapped types
Lookup types
Mapped type modifiers
Conditional types
The infer keyword
Built-in conditional types
The polymorphic this type
Ambient declarations
Type declarations – .d.ts
Summary
Working with Functions
Working with functions in TypeScript
Function declarations and function expressions
Function types
Trailing commas in function arguments
Functions with optional parameters
Functions with default parameters
Functions with REST parameters
Function overloading
Specialized overloading signature
Function scope
Immediately invoked functions
Tag functions and tagged templates
Asynchronous programming in TypeScript
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
Object-Oriented Programming with TypeScript
Classes
Strict property initialization
Inheritance
Depth of the inheritance tree (DIT)
Access modifiers
The public access modifier
The private access modifier
The protected access modifier
Parameter properties
Class expressions
Static members
Optional members
Read-only properties
Method overriding
Generic classes
Generic constraints
Multiple types in generic type constraints
The new operator in generic types
Association, aggregation, and composition
Association
Aggregation
Composition
Mixins (multiple inheritance)
The diamond problem
Implementing mixins
Iterables
Abstract classes
Interfaces
SOLID principles, encapsulation, and polymorphism
SOLID – the single responsibility principle
Encapsulation
SOLID – the open/closed principle
Polymorphism
SOLID – the Liskov substitution principle 
SOLID – the interface segregation principle
SOLID – the dependency inversion principle
Summary
Working with Dependencies
Third-party dependencies
Package management tools
The rise and fall of package management tools
npm
Type definitions
Modules with native support for TypeScript
Modules with external support for TypeScript
Modules with no support for TypeScript
The ECMAScript specification type definitions (lib.d.ts)
External TypeScript helpers (tslib)
Internal modules (module and namespace)
Nested internal modules
Cross-file internal modules
Internal module aliases
Compiling internal modules
External modules
Module loaders and module definition syntaxes
External modules at design time and runtime
ES6 modules (runtime and design time)
Legacy external modules (design time only)
AMD modules (runtime only)
CommonJS modules (runtime only)
UMD modules (runtime only)
SystemJS modules (runtime only)
Modules summary
Managing dependencies in OOP
Dependency injection versus dependency inversion
Inversion of control containers
InversifyJS basics
Circular dependencies
Summary
Understanding the Runtime
The execution 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 a function context
The call, apply, and bind methods
Prototypes
Instance properties versus class properties
Prototypal inheritance
The prototype chain and property shadowing
Accessing the prototype of an object
The new operator
Closures
Static variables powered by closures
Private members powered by closures
Summary
Functional Programming with TypeScript
FP concepts
Pure functions
Side effects
Referential transparency
Immutability
Functions as first-class citizens
Lambda expressions
Function arity
Higher-order functions
The benefits of FP
Is TypeScript a FP language?
FP techniques
Composition
Partial application
Currying
Pipes
Pointfree style
Recursion
Category theory
Functor
Applicative
Maybe
Either
Monad
Real-world FP
Immutable.js
Ramda
React and MobX
Summary
Working with Decorators
Prerequisites
Annotations versus decorators
The class decorators
The method decorators
The property decorators
The parameter decorators
Decorators with arguments
The reflect metadata API
The decorator factory
Summary
Automating Your Development Workflow
A modern development workflow
Prerequisites
Node.js
Visual Studio Code
Git and GitHub
Companion source code
Source control tools
Package management tools
The TypeScript compiler
Linting tools
Working with npm scripts
Gulp
Controlling the gulp task execution order
Passing in a callback to the task definition function
Returning a promise
Returning a stream
Webpack
Webpack development server
Unit testing and test coverage
Visual Studio Code
Quick fixes
Debugging utilities
Source control utilities
ts-node
Continuous integration (CI) tools
Scaffolding tools
Why does the command line win?
Summary
Node.js Development with TypeScript
Understanding Node.js
Understanding non-blocking I/O
The main components of Node.js
V8
Libuv
Bindings
The Node.js core API (node-core)
Node.js environment versus browser environment
The Node.js ecosystem
The Node.js core API
The style of the Node.js core API
The npm ecosystem
Setting up Node.js
Node.js development
Working with the filesystem
Working with databases
Working with REST APIs
Hello world (http)
Hello world (Express.js)
Routing with Express
Express middleware
Architecting Node.js application – the MVC design pattern
Model
Repository
Controller
Database
View
Index
Controllers and routing with inversify-express-utils
Model, repository, database, and view
Types
Controller
InversifyJS configuration
Index
Other applications of Node.js
Summary
Frontend Development with React and TypeScript
Working with React
About the sample application
Serving a React application with Node.js
Working with react-dom and JSX
Working with the react-router
Working with React components
Components as classes
Properties and state
Functional stateless components
React component life cycle
Smart components and dumb components
Working with MobX
Understanding the MobX architecture
Working with actions and observables
Dependency injection in MobX
MobX alternatives
Development tools
Summary
Frontend Development with Angular and TypeScript
Working with Angular
About the sample application
Serving an Angular application with Node.js
Bootstrapping an Angular application
Working with NgModules
Working with Angular components
Our first component
Components and directives
Data binding
Working with @Attribute and @Input
Using structural directives
Using the <ng-content> directive
Working with @Output and EventEmitter
Working with the component's host
Working with the Angular router
Angular component life cycle hooks
Working with services
Smart components and dumb components
Dependency injection in Angular
Summary
Application Performance
Prerequisites
Google Chrome
Node.js
Performance and resources
Common performance metrics
Availability
Response time
Processing speed
Bandwidth
Latency
Scalability
Performance analysis
Network performance analysis
Network performance and user experience
Network performance best practices and rules
GPU performance analysis
Frames per second (FPS)
CPU performance analysis
Memory performance analysis
The garbage collector
Performance analysis in Node.js applications
Performance automation
Performance optimization automation
Performance monitoring automation
Performance testing automation
Exception handling
The Error class
The try...catch statements and throw statements
Summary
Application Testing
Testing terminology
Assertions
Specs
Test cases
Suites
Spies
Dummies
Stubs
Mocks
Test coverage
Prerequisites
Mocha
Chai
Sinon.JS
nyc
Webpack
Enzyme
SuperTest
PM2
Nightwatch.js and ChromeDriver
Testing methodologies
Test-driven development (TDD)
Behavior-driven development (BDD)
Tests plans and test types
Unit tests
Integration tests
Regression tests
Performance and load tests
End-to-end (e2e) tests
User-acceptance tests (UAT)
The example application
Unit tests and integration tests with Mocha
Back to basics
Testing asynchronous code
Asserting exceptions
Testing a web service with SuperTest
Working with tests suites
Isolating components with Sinon.JS
jsdom
Testing React web components with Enzyme
TDD versus BDD with Mocha and Chai
End-to-end tests with Nightwatch.js
Summary
Working with the TypeScript Compiler and the Language Services
The TypeScript compiler's internal architecture
Scanner
Lexemes and tokens
Parser
AST
Symbols
Binder
Type checker
Emitter
Language service
Understanding the abstract syntax tree (AST)
TypeScript AST Viewer
Sample application
interfaces.ts
katana.ts
ninja.ts
main.ts
broken.ts
Traversing the TypeScript AST
Working with ts-simple-ast
Traversing the AST with ts-simple-ast
Diagnostics with ts-simple-ast
Accessing class details with ts-simple-ast
Accessing module details with ts-simple-ast
Accessing the language services API
Implementing a yUML compiler
VS Code extensions
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Over the past decade, the JavaScript code base of an average web application has been growing exponentially. However, the current version of JavaScript was designed several years ago and lacks some features necessary to cope with the level of complexity that we may find in a modern JavaScript application. Owing to these missing features, maintainability problems have arisen.
The ECMAScript 2015 specification is meant to solve some of the maintainability issues of JavaScript, but its implementation is in progress, and many incompatible web browsers are still in use today. For these reasons, wide adoption of the ECMAScript 2015 specification is expected to be a slow process.
To resolve the maintainability and scalability problems of JavaScript, TypeScript was publicly announced in October 2012, after 2 years of internal development at Microsoft:
Some developers with many years, experience in web development will find it challenging to define a large-scale JavaScript application. When referring to this term, we will avoid considering the number of lines of code in the application. It is much better to consider the number of modules and entities in an application, and the number of dependencies between them as units of measurement of the application’s scale. We will define large-scale applications as nontrivial applications that require significant developer effort to be maintained.
Learning TypeScript 2.x Second Edition, introduces many of the TypeScript features in a simple and easy-to-understand format. This book will teach you everything you need to know to implement a large-scale JavaScript application using TypeScript. Not only does it teach TypeScript’s core features, which are essential to implement a web application, but it also explores some powerful development tools, design principles, and good practices, and demonstrates how to apply them to real-life applications.
The second edition has been upgraded and extended, with five additional chapters that cover topics such as functional programming, advanced type system features, an introduction to frontend development with React and Angular, an introduction to Node.js development, and an introduction to the internal APIs of the TypeScript compiler.
The new edition contains a total of 15 chapters. Seven of these chapters are completely new and were not included in the first edition.
If you are a developer aiming to learn TypeScript to build attractive web applications, this book is for you. No prior knowledge of TypeScript is required. However, a basic understanding of JavaScript would be an added advantage.
Chapter 1, Introducing TypeScript, helps you to get familiar with the TypeScript basics. This chapter explores the purpose, main features, and benefits of the TypeScript programming language.
Chapter 2, Working with Types, teaches you how to make the most out of the TypeScript type annotations and its type inference system. This chapter will teach you how to use powerful features, such as union types or mapped types.
Chapter 3, Working with Functions, covers how to work with functions in depth. This chapter will teach you how to take advantage of the power of functions and asynchronous programming in TypeScript.
Chapter 4, Object-Oriented Programming with TypeScript, deals with the core concepts of the object-oriented programming (OOP) paradigm, such as polymorphism, inheritance, and encapsulation. This chapter also explores some OOP best practices, such as the SOLID principles.
Chapter 5, Working with Dependencies, explores how to work with application dependencies, third-party dependencies, and type definitions. This chapter explores multiple module systems, such as CommonJS and ES6 modules, and concepts such as dependency injection.
Chapter 6, Understanding the Runtime, teaches you how the JavaScript runtime works and helps you gain a good understanding of concepts such as the event loop, closures, and hoisting.
Chapter 7, Functional Programming with TypeScript, explores the core building blocks of the functional programming paradigm, including concepts such as function composition, function partial application, and referential transparency.
Chapter 8, Working with Decorators, showcases how to apply and declare decorators and how to use decorators to create and read metadata that can be used to power tools such as testing frameworks and inversion of control containers.
Chapter 9, Automating Your Development Workflow, focuses on how to automate certain tasks in your development workflow and reduce the number of integration issues, using tools, such as TSLint, webpack, Gulp and npm scripts.
Chapter 10, Node.js Development with TypeScript, teaches you how to use REST APIs powered by Node.js and TypeScript.
Chapter 11, Frontend Development with React and TypeScript, enables you to learn how to develop single-page web applications powered by React and TypeScript.
Chapter 12, Frontend Development with Angular and TypeScript, teaches you how to develop single-page web applications powered by Angular and TypeScript.
Chapter 13, Application Performance, makes you understand how the availability of system resources can affect the performance of a TypeScript application, and how to use the Node.js inspector and the Chrome Development tools to analyze the performance of a TypeScript application.
Chapter 14, Application Testing, teaches you how to implement automated tests such as unit tests or end-to-end tests powered by tools such as Mocha, Chai, Sinon.JS, Supertest, and Karma.
Chapter 15, Working with the TypeScript Compiler and the Language Services, explores how to leverage the TypeScript language services to create your own code analysis tools.
Nothing external is required for this book. You will be able to make the most out of this book by following just what’s mentioned in this book.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.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.packtpub.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/remojansen/LearningTypeScript. In case there's an update to the code, it will be updated on the existing GitHub repository. The GitHub repository will include detailed instructions about how to run each of the examples.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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/LearningTypeScript2xSecondEdition_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "If we try to predict the result of invoking the isIndexPage, we will need to know the current state."
A block of code is set as follows:
function addMany(...numbers: number[]) { numbers.reduce((p, c) => p + c, 0); }
Any command-line input or output is written as follows:
npm install typescript -g
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.packtpub.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.
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 packtpub.com.
This book aims to provide you with a broad overview of TypeScript's features, its limitations, and its ecosystem. You will learn about the TypeScript language, development tools, design patterns, and recommended practices.
This chapter will give you an overview of the history behind TypeScript and introduce you to some of its basics.
In this chapter, you will learn about the following concepts:
The TypeScript architecture
Type annotations
Variables and primitive data types
Operators
Flow control statements
Functions
Classes
Interfaces
Namespaces
In this section, we will focus on TypeScript's internal architecture and its original design goals.
The following list describes the main design goals and architectural decisions that shaped the way the TypeScript programming language looks today:
Statically identify JavaScript constructs that are likely to be errors
: The engineers at Microsoft decided that the best way to identify and prevent potential runtime issues was to create a strongly-typed programming language and perform static type checking at compile time. The engineers also designed a language services layer to provide developers with better tools.
High compatibility with existing JavaScript code
: TypeScript is a superset of JavaScript; this means that any valid JavaScript program is also a valid TypeScript program (with a few small exceptions).
Provide a structuring mechanism for larger pieces of code
: TypeScript adds class-based object-orientation, interfaces, namespaces, and modules. These features will help us to structure our code in a much better way. We will also reduce potential integration issues within our development team and our code will become easier to maintain and scale by adhering to the best object-oriented principles and recommended practices.
Impose no runtime overhead on emitted programs
: It is common to differentiate between design time and execution time when thinking about TypeScript. We use the term
design time
or
compile time
to refer to the TypeScript code that we write while designing an application, while we use the term
execution time
or
runtime
to refer to the JavaScript code executed after compiling some TypeScript code.
TypeScript adds some features to JavaScript, but those features are only available at design time. For example, we can declare interfaces in TypeScript, but since JavaScript doesn't support interfaces, the TypeScript compiler will not declare or try to emulate this feature at runtime (in the output JavaScript code).
The Microsoft engineers provided the TypeScript compiler with some mechanisms, such as code transformations (converting TypeScript features into plain JavaScript implementations) and type erasure (removing static type notation), to generate clean JavaScript code. Type erasure removes not only the type annotations, but also all the TypeScript-exclusive language features such as interfaces.
Furthermore, the generated code is highly compatible with web browsers as it targets the ECMAScript 3 specification by default, but it also supports ECMAScript 5 and ECMAScript 6. In general, we can use the TypeScript features when compiling to any of the available compilation targets, but sometimes some features will require ECMAScript 5 or a higher version as the compilation target.
Align with current and future ECMAScript proposals
: TypeScript is not just compatible with existing JavaScript code; it is also compatible with some future versions of JavaScript. At first glance, we may think that some TypeScript features make it quite different from JavaScript, but the reality is that all the features available in TypeScript (except the type system features) follow the ECMAScript proposals, which means that many of the TypeScript files will eventually be available as native JavaScript features.
Be a cross-platform development tool
: Microsoft released TypeScript under the open source Apache license and it can be installed and executed in all major operating systems.
The TypeScript language has three main internal layers. Each of these layers is, in turn, divided into sublayers or components. In the following diagram, we can see the three layers (three different shades of gray) and each of their internal components (boxes):
Each of these main layers has a different purpose:
Language
: Features the TypeScript language elements.
Compiler
Performs the parsing, type checking, and transformation of your TypeScript code to JavaScript code.
Language services
: Generates information that helps editors and other tools provide better assistance features, such as IntelliSense or automated refactoring.
IDE integration (VS Shim)
: The developers of the IDEs and text editors must perform some integration work to take advantage of the TypeScript features. TypeScript was designed to facilitate the development of tools that help to increase the productivity of JavaScript developers. Because of these efforts, integrating TypeScript with an IDE is not a complicated task. A proof of this is that the most popular IDEs these days include good TypeScript support.
As we have already learned, TypeScript is a typed superset of JavaScript. TypeScript added a static type system and optional static type annotations to JavaScript to transform it into a strongly-typed programming language.
TypeScript's type analysis occurs entirely at compile time and adds no runtime overhead to program execution.
TypeScript supports the following arithmetic operators. We must assume that variable A holds 10 and variable B holds 20 to understand the following examples:
Operator
Description
Example
-
Subtracts the second operand from the first.
A - B will give -10
+
Adds two operands.
A + B will give 30
*
Multiplies both the operands.
A * B will give 200
**
Multiplies the first operand by itself a number of times which is indicated by the second operand.
A ** B will give 1e+20
%
This is the modulus operator and remainder after an integer division.
B % A will give 0
/
Divides the numerator by the denominator.
B / A will give 2
--
Decreases an integer value by one.
A-- will give 9
++
Increases an integer value by one.
A++ will give 11
TypeScript supports the following logical operators. To understand the examples, you must assume that variable A holds 10 and variable B holds 20:
Operator
Description
Example
&&
Known as the logical AND operator. If both the operands are nonzero, then the condition becomes true.
(A && B) is true.
||
Known as the logical OR operator. If any of the two operands are nonzero, then the condition becomes true.
(A || B) is true.
!
Known as the logical NOT operator. It is used to reverse the logical state of its operand. If a condition is true, then the logical NOT operator will make it false.
!(A && B) is false.
TypeScript supports the following bitwise operators. To understand the examples, you must assume that variable A holds 2 as value and variable B holds 3 as value:
Operator
Description
Example
&
Known as the bitwise AND operator, it performs a boolean AND operation on each bit of its integer arguments.
(A & B) is 2
|
Known as the bitwise OR operator, it performs a boolean OR operation on each bit of its integer arguments.
(A | B) is 3.
^
Known as the bitwise XOR operator, it performs a boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.
(A ^ B) is 1.
~
Known as the bitwise NOT operator, it is a unary operator and operates by reversing all bits in the operand.
(~B) is -4
<<
Known as the bitwise shift-left operator. It moves all bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by two, shifting two positions is equivalent to multiplying by four, and so on.
(A << 1) is 4
>>
Known as the bitwise shift-right with sign operator. It moves all bits in its first operand to the right by the number of places specified in the second operand.
(A >> 1) is 1
>>>
Known as the bitwise shift-right with zero operators. This operator is just like the >> operator, except that the bits shifted from the left are always zero.
(A >>> 1) is 1
This section describes the decision-making statements, the looping statements, and the branching statements supported by the TypeScript programming language.
The for