TypeScript 2.x By Example - Sachin Ohri - E-Book

TypeScript 2.x By Example E-Book

Sachin Ohri

0,0
41,99 €

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

Mehr erfahren.
Beschreibung

Leverage the power of Typescript 2.0 using real-world examples

About This Book

  • Begin with the fundamentals of TypeScript and learn how to write better JavaScript code
  • Build three amazing applications throughout the book
  • Leverage the power of tools such as Angular 2 and NativeScript to build for the web as well as for mobile

Who This Book Is For

Web developers who would like to learn how to use TypeScript to build amazing applications will benefit from this book.

What You Will Learn

  • Design your first project in Visual Studio
  • Learn about the different data types in TypeScript
  • Create web applications in an object-oriented fashion using TypeScript
  • Build a Trello application using TypeScript's complex features.
  • Explore the tools available in a web application ecosystem to write unit test cases
  • Deploy web applications to cloud and assign resources to the application

In Detail

The TypeScript language, compiler, and open source development toolset brings JavaScript development up to the enterprise level. It allows you to use ES5, ES6, and ES7 JavaScript language features today, including classes, interfaces, generics, modules, and more. Its simple typing syntax enables building large, robust applications using object-oriented techniques and industry-standard design principles.

This book aims at teaching you how to get up and running with TypeScript development in the most practical way possible. Taking you through two exciting projects built from scratch, you will learn the basics of TypeScript, before progressing to functions, generics, promises, and callbacks. Then, you'll get to implement object-oriented programming as well as optimize your applications with effective memory management. You'll also learn to test and secure your applications, before deploying them. Starting with a basic SPA built using Angular, you will progress on to building, maybe, a Chat application or a cool application. You'll also learn how to use NativeScript to build a cool mobile application. Each of these applications with be explained in detail, allowing you to grasp the concepts fast.

By the end of this book, you will have not only built two amazing projects but you will also have the skills necessary to take your development to the next level.

Style and approach

Example-based approach to get you quickly started with Typescript

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 444

Veröffentlichungsjahr: 2017

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



TypeScript 2.x By Example

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.

 

First published: December 2017

 

Production reference: 1191217

 

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

 

ISBN 978-1-78728-003-8

 

www.packtpub.com

Credits

Author

Sachin Ohri

Copy Editor

Safis Editing

Reviewer

Sandeep Singh

Project Coordinator

Ulhas Kambali

Commissioning Editor

Richa Tripathi

 

Proofreader

Safis Editing

Acquisition Editor

Denim Pinto

Indexer

Rekha Nair

ContentDevelopmentEditor

Nikhil Borkar

Graphics Coordinator

 

Tom Scaria

Technical Editor

Madhunikita Sunil Chindarkar

Production Coordinator

 

Nilesh Mohite

About the Author

Sachin Ohri is a Technology Architect with a keen interest in web-based technologies. He has been writing web applications for more than a decade, with technologies such as .NET, JavaScript, Durandal, Angular, and TypeScript.

He works on providing technical solutions, including architectural design, technical support, and development expertise, to Fortune 500 companies.

He considers himself a polygot developer willing to learn new languages and technology. Recently, he has been focusing on cloud-based web application development with Microsoft Azure. He holds various Microsoft certifications, such as Microsoft Azure Architect, Microsoft ASP.NET MVC web application, and Microsoft Programming with C#.

Acknowledgments

It would not have been possible to write this book without the complete support of my family and friends. They have been there, inspiring and motivating me along the way. Thanks to my friends who provided technical support and guidance during the course of this project.

Special thanks to the Packt team, Anurag, Nikhil, and Denim, who have been very encouraging and made the entire process smooth.

About the Reviewer

Sandeep Singh has over 15 years of experience in web application development. He currently works as a senior solution architect at one of the Fortune 100 companies. He specializes in JavaScript, Angular, and React.

I would like to thank my family for supporting me through this endeavor.

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.comand 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.

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/1787280039. If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

This book is dedicated to Shaurya and Inaya.
TypeScript 2.x By Example

 

 

 

 

 

 

 

 

 

 

Build engaging applications with TypeScript, Angular, and NativeScript on the Azure platform

 

 

 

 

 

 

 

 

 

 

Sachin Ohri

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Our First Application – Sports News Combinator

Sports News Combinator (SNC)

Downloading the code

The feature set of SNC

Type System

Variables

The var keyword

Let and const keywords

Types in TypeScript

Type annotation

Primitive types

Number

String

Boolean

Arrays

Tuples

Any

Void

Null and undefined

Union types

Type inference

Type checking

Classes in TypeScript

Object-oriented programming in TypeScript

Understanding classes

Access modifiers

Public

Private

Protected

Readonly

Transpiled JavaScript from classes

ES6 JavaScript

ES5 JavaScript

SNC – 101

Angular – the superhero framework

SPAs

Angular – the concepts

Angular – the architecture

SNC – the architecture

SNC – code setup

Angular CLI  setup

Application setup

SNC – folder structure

Creating our model

First component – NewsComponent

Template

Component class

Metadata of the component

Import

newsComponent

newsComponent business logic

newsComponent template logic

SNC – running the code

Summary

Sports News Combinator – Adding Features

Functions

Types in functions

Arrow functions

The this keyword in arrow functions

Optional and default parameters

Rest parameters

Function overloads

Classes in TypeScript

Class definition

Constructors

Constructor parameters

Properties and methods

Properties

Accessors

Methods

Static properties

Inheritance

Super

Abstract class

Interfaces

Definition

Duck typing

Extending interfaces

Implementing interfaces

Adding features to SNC

Restructuring the models

Adding interface to the Article class

Modifying the news model

Core components

The header component

The component file

The HTML file

The footer component

The app component

Templates and interpolation

Templates

Directives

The Angular loading process for directives

Angular built-in directives

The *ngIf directive

The *ngFor directive

Bindings

Interpolation

Property binding

Two-way binding

Summary

Sports News Combinator – the Final Version

Decorators

Decorator design pattern

Decorators in TypeScript

Definition of decorators in TypeScript 

Decorator factory

Class decorator

Passing parameters to the decorator

Overriding constructors in decorators

Method decorator

Property decorator

Parameter decorator

Decorators in SNC

Additional features in SNC

Adding services in SNC

Creating a service

Registering our service

Injecting the service

Implementing HTTP calls in SNC

Observables in HTTP

HTTP request flow with observables

Implementing the HTTP request

Subscribing to HTTP response

Routing in SNC

Defining routes

Application routes

Adding to the router module

Importing in the app module

Implementing a router link

Accessing routes in NewsComponent

Final product

Summary

Application 2 – Trello

An introduction to the sample Trello application

Application overview

Technical overview

TypeScript namespace and modules

The universal namespace

The TypeScript namespace

The export keyword

Nested namespace

Namespaces transpired to JavaScript

TypeScript modules

Definition

Exporting a module

Importing a module

TypeScript Generics

Definition

Functions

Classes

Generic constraints

Sample Trello application 

Application Architecture

Code setup

The Trello homepage

Models

The homepage component

Board service

Homepage – initialize the data

OnInit

OnDestroy

OnChange

Homepage – template

Homepage – add a new board

Running the application

Trello – the board component

Routing

Routing in the Board component

Board component – populating the data

Board component – passing data to child components

Passing data to child components with @Input

Passing data from a child component to the parent component

Summary

Trello - Adding Features

Iterators

Iterators in JavaScript

Iterators in TypeScript

Custom iterators in TypeScript

For...of and for...in loops in TypeScript

Asynchronous programming using TypeScript

Callback functions

Callback in TypeScript

CleanUp the function

Promises

Promise API

Handling the response

Chaining the promises

Async-await

Error handling in async-await

Adding features to Sample Trello app

Using promises in sample Trello

Board JSON

Implement promises

Add HTTP dependency

Logic for HTTP call

Call from the Homepage component

Functional implementation

Implement – adding a new task

Board component

The enableAddTask function

The addtaskonEnter function

The addTask method

The clearTask method

The addtaskonBlur method

Implement – adding a new subTask

Task template

Change title of board, task, and subTask

Modify the title of a board

Reflecting the changes on the Homepage

Data formatting in Angular

Built-in pipes

Custom pipes

Sorting pipe for Trello

Adding pipe dependency

Using the custom pipe

Understanding dependency injection in Angular

Managing the dependencies

Summary

Testing the Trello Application

Fundamentals

Challenges in testing

Test-driven development 

Unit testing versus end-to-end testing

Unit testing

End-to-end testing

Structure of a test

Mocking

Tools for testing

Jasmine

Karma

Installing and configuring Jasmine and Karma

Installation

Karma-CLI

Other dev dependencies

Jasmine typing

Configuration

Folder and file structure for the test project

Writing test for pipes

Creating a new file

Writing the test case

Describe function

The beforeEach function

The it function

Executing the test cases

Writing test cases for the services class

Creating a new file

Writing the test case

The describe function

The beforeEach function

The it function

Writing test cases for isolated component

Creating a new file

Writing the test case

Implementing the test cases

Writing the test cases for integrated components

Setting up the integrated test

Implementing the test cases

The describe function

First beforeEach function

Second beforeEach function

The it functions

Check boards on the user interface

Test new board creation

Test cases for other components

Summary

Trello - Using Angular CLI

Introducing Angular CLI

Setting up Angular CLI

Angular CLI help command

Generating an application with Angular CLI

File overview

ng new – flags and customization

Customizing the app

App routing file

Angular CLI file

Generating files for the application

Generating a component

Component options in Angular CLI

The flat option

The inline-template option

The inline style option

The spec option

Generating a service

Service options in Angular CLI

The flat option

The spec option

The module option

Generating a pipe

Generating a module

Providing the login module in the app module

Adding components, services, and more in the login module

Adding routing to the modules

Generating TypeScript files

Generating a class

Generating an interface

Generating an enum

Building an Angular app

The build process

The build command

Building the application in dev mode

Dist folder details

The API folder

Favicon

The index.html file

The inline bundle file

The main bundle file

The polyfill bundle file

The style bundle file

The vendor bundle file

The map files

Building the application in production mode

Dist folder details

The bundle files

Serving an Angular app

The ng serve options

Linting an Angular application

Linting rules

Linting options

Linting the Trello application

Code coverage using Angular CLI

Code coverage for the Trello application

Summary

Trello Mobile – Using NativeScript

What is NativeScript?

NativeScript design

NativeScript architecture

NativeScript modules

NativeScript versus web applications

Setting up your NativeScript environment

NativeScript CLI

Installing mobile platform dependencies

Installing an Android Virtual Device

Developing the Sample Trello application using NativeScript

Creating the application skeleton

Running the default NativeScript application

Default folder structure for a NativeScript application

Folder structure in Visual Studio Code

The app folder

The node_modules folder

The platforms folder

The hooks folder

Developing the Homepage component

Cleaning up the existing content

Trello Board models

Implementing the Trello service 

Updating the app.module file with the Trello service

Implementing the Homepage component

The Homepage component file

The Homepage style sheet file

The Homepage HTML file

UI elements in the Homepage template

StackLayout

Label

ListView

Binding in a NativeScript Angular template

Event binding

Stitching the Homepage component

The application so far

Executing the run command

Debugging the application

The debug command

Developing the Board component

Board component template

Changes in routing for BoardComponent

Executing the code

NativeScript UI elements

Summary

Deploying Sample Trello on the Cloud Using Microsoft Azure

Azure Cloud as a deployment platform

Benefits of a cloud platform

Efficient hosting and deployment

Scaling

Maintenance

Monitoring

Economy

Deployment options in Microsoft Azure

Platform as a Service (PaaS)

Software as a Service (SaaS)

Deploying Sample Trello using a web app service – FTP

Managing the web app service 

Creating a web app

Resource group

App service plan

Deploying the Sample Trello application

Creating deployment credentials

Deploying the code on the web app

web.config file for URL redirection

The result

Deploying Sample Trello using a web app service – GitHub

Integration with GitHub

Configuring GitHub

Running the application

Adding the dist folder to GitHub

Adding application settings

Continuous deployment and monitoring

Web application monitoring

Summary

Getting Started with TypeScript

The current state of JavaScript

The not-so-good parts of JavaScript

Features

Type inference

Arrays

Equality comparison

Null or undefined

TypeScript to the rescue

Benefits of TypeScript

TypeScript comparison with JavaScript

Alternatives to TypeScript

TypeScript features

Features

Data types

Control flow analysis

Encapsulation

Inheritance

Interface

Shapes

Decorators

TypeScript syntax and keywords

Installation and setup

Installation of TypeScript

TypeScript editors

Visual Studio

VS Code

TypeScript compiler

TypeScript to-do list application

todo.ts

Classes in TypeScript

Functions in TypeScript

Debugging TypeScript code

Playground

Summary

Preface

TypeScript has been a revolution in client-side development. It has taken mainstream concepts, such as types, classes, interfaces, generics, and decorators, and introduced them to the JavaScript world. The best part is that TypeScript does not introduce any new language but provides features that are currently in TC39 discussions for JavaScript.

All JavaScript code is valid TypeScript code, which allows developers to migrate and use TypeScript in the existing application. In this book, we will comprehensively cover TypeScript features, from basic features to advanced ones. We will introduce the features along with hands-on application development to aid better understanding.

Along with TypeScript, we will also look at Angular and learn the intricacies of the framework. We will be developing two applications along the way and both these applications will use Angular as their frontend framework.

By end of this book, we will look at the NativeScript framework, which will help us convert our Angular/TypeScript applications to native mobile platform applications. We will also look at Microsoft Azure as our cloud platform to deploy our web applications.

The purpose of this book is to provide readers with the knowledge of TypeScript and Angular so that they can build real-world applications effectively and efficiently.

What this book covers

Chapter 1, Getting Started with TypeScript, provides us with an introduction to TypeScript and its features. We will create a small ToDo application, which provides insights into basic TypeScript features.

Chapter 2, Our First Application – Sports News Combinator, introduces us to the basic concepts of TypeScript and Angular. We'll take a look at types in TypeScript and how to set up an Angular application, along with the concept of components.

Chapter 3, Sports News Combinator – Adding Features, covers important concepts of TypeScript, such as interfaces, classes, and object-oriented programming. In Angular, we look at data binding, directives, and templates.

Chapter 4, Sports News Combinator – the Final Version, adds final features to the application and, in doing so, covers decorators, dependency injection, routing, and HTTP using RxJS observables in Angular.

Chapter 5, Application 2 – Trello, is our second application. With this application, we'll look at generics, namespaces, and modules in TypeScript. We'll also look at some of the advanced features of Angular, such as communication between components and life cycle hooks.

Chapter 6, Trello – Adding Features, takes us deeper into the feature set of TypeScript and Angular. We cover iterators and async programming using callbacks, promises, and observables. In Angular, we'll look at pipes and dependency injection.

Chapter 7, Testing the Trello Application, introduces us to the testing features provided in Angular. We look at the unit testing of services, pipes, and components.

Chapter 8, Trello – Using Angular CLI, provides us with the details of the Angular CLI and its feature set. We look at creating new applications, generating components, services, pipes, classes, and interfaces. Then, we shift our focus to features such as building, serving, and linting any Angular-based web application.

Chapter 9, Trello Mobile – Using NativeScript, allows us to convert our web application into a native mobile application. In this chapter, we will look at the NativeScript framework and see how we can use its features to create Android and iOS applications from our web application.

Chapter 10, Deploying Sample Trello on the Cloud Using Microsoft Azure, explains cloud as our deployment platform. We will look at Azure as Platform as a Service and deploy our application using FTP and GitHub. We will also look at how Azure enables us to perform continuous deployment for our application.

What you need for this book

All our examples and code snippets use TypeScript and Angular, which can be developed in any IDE. We prefer to use Visual Studio Code but you can use any IDE that you are comfortable with, such as Sublime, Atom, and WebStorm, among others.

Who this book is for

This book does not assume any prerequisite knowledge of TypeScript or Angular from its readers. We cover all the concepts of TypeScript and Angular, starting from the basic ones and moving towards the advanced concepts.

We do cover the concepts of JavaScript with respect to TypeScript, but it would be helpful if you have some basic understanding of JavaScript.

All our applications use basic HTML and CSS; although not necessary, having a basic knowledge of these can help readers design applications more easily. We do provide the entire code base, including all the HTML and CSS for the readers to refer.

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: "The next lines of code read the link and assign it to the to theBeautifulSoupfunction." A block of code is set as follows:

#import packages into the project from bs4 import BeautifulSoup from urllib.request import urlopen import pandas as pd

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) Any command-line input or output is written as follows:

C:\Python34\Scripts> pip install -upgrade pip

C:\Python34\Scripts> pip install pandas

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: "In order to download new modules, we will go toFiles|Settings|Project Name|Project Interpreter."

Warnings or important notes appear like this.
Tips and tricks appear like this.

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 email [email protected], 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.

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.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://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 to our website using your email address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

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

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/TypeScript-2x-By-Example. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

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 [email protected] 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 [email protected], and we will do our best to address the problem.

Our First Application – Sports News Combinator

In the last chapter, we got a glimpse into the world of TypeScript. We looked at the features of TypeScript, which allow us to write more manageable, robust, and error-free code. TypeScript is a powerful language that provides the right balance between the flexibility of JavaScript and features, such as types and interfaces, which provide checks at design and compile time.

In this chapter, we will start by digging deeper into the feature set of TypeScript, and will also introduce the Angular framework. As with the subject of this book, we will use real-world examples to gain a better understanding of the features.

This chapter will focus on the following topics:

Sports News Combinator (SNC)

: We will start by introducing our first application and its feature set, which we will build.

Types in TypeScript

: Types play an important role in TypeScript, and we will delve deeper into the various types available in TypeScript, type inference, and type declaration.

Classes in TypeScript

: To be able to build robust web applications, we have classes. TypeScript implements classes to provide the object-oriented feature.

Introduction to Angular

: The SNC application is built with TypeScript and Angular, so it is important to introduce Angular and its basic concepts, such as components and data binding.

Project setup, configuration, and code setup

: In this section, we will start building our application by first looking at various ways to create

single-page applications

(

SPAs

) with Angular, and then using the Angular CLI to create our application's skeleton.

The architecture of SNC:

We will look at the high-level architecture of SNC and discuss the various components that will be created.

Building our first component:

We will be creating our first component, which will be used to display the news content on the page.

By the end of this chapter, we will have a simple working app with hardcoded data, as well as an understanding of types in TypeScript, and the basic fundamentals of Angular.

Sports News Combinator (SNC)

SNC is a single-page web application that provides a unified interface to view the latest sports news from various news outlets. We will be fetching news from NFL, Fox Sports, ESPN, and BBC Sport. We will have four tabs in SNC, each providing the top 10 articles from the respective news outlet. When the user clicks on any of the article links, SNC will redirect the user to the respective website.

This application will be large enough to showcase application features, and small enough not to distract us with the intricacies of applications, and will help us learn the fundamental concepts of TypeScript and Angular.

The following screenshot shows the final version of our application:

Downloading the code

The code for SNC can be downloaded from GitHub at https://github.com/sachinohri/SportsNewsCombinator.git. We will build our application incrementally, with each chapter adding features while discussing the concepts of TypeScript and Angular. So, it makes sense that we provide code for each chapter as well, apart from the final application. To achieve this goal, we have created multiple folders under the main master branch, with each folder providing the final code, which we will create at the end of each chapter. The naming convention for each folder is based on the chapter number.

For this chapter, you can find the code in the Chapter 02 folder, as shown in the following screenshot:

The feature set of SNC

In this chapter, we will be focusing on creating the bare minimum of our application to showcase the features of TypeScript and Angular. SNC will have the following functionalities by the end of this chapter:

The application will have just one tab to show the news from the NFL network.

Data in this tab will be hardcoded just to show how data binding works. We will be making a live web service call  in

Chapter 4

,

Sports New Combinator - the Final Version

.

We will design a single component for our application, which will host the main content.

 

Type System

If there is one feature in TypeScript that stands out from its competitor, it is Type System, and how TypeScript uses types to help write better code. Types in TypeScript are one of the easiest features to understand and use, thus providing the maximum productivity boost for a new developer to TypeScript.

To develop any application with TypeScript, understanding types and their features is very important. Hence, we will look at the following topics in this section, which will then help us when we start working on our application:

Variables

: We will start by looking at how to declare variables and constants in TypeScript. We will also look at the 

let

 and

const

keywords, which were introduced in ES 2015 to provide better scoping. 

Types

: We will then shift our focus to looking at types provided by TypeScript, which include both primitive and custom types.

Type inference

: Then we will look at how TypeScript uses type inference to help identify the types.

Type compatibility

: TypeScript has a feature wherein we can relate types based on members only; we will take a look at this with an example.

Types are a TypeScript concept and are not emitted in the transpiled JavaScript. They are only used at design and compile time.

Variables

If you have done any JavaScript programming, you will be aware of the var keyword for declaring variables. In ES 2015, a couple of new keywords were introduced to allow declaring variables, namely let and const. The var keyword allowed us to declare a variable, but it had its quirks with regard to how scoping and access to the variables worked; let tries to solve this problem. 

The var keyword

Variables declared with the var keyword have a global scope in which they are declared; this means that they can be accessed by any function sharing the same scope. The following example shows the scope of the variable value in innerFunction:

Also, variables declared with the var keyword are subject to hoisting. This means that if we declare a variable at the end of a function, the runtime will hoist it to the top and we will not have any error if we would have used that variable before being declared. In the following example, we see an example of hoisting. Although the value variable was declared at line 9, we were able to access it at lines 3 and 6. When this function is executed, the JavaScript runtime hoists the variable declaration to the top of the function, and hence, is available at lines 3 and 6. The output of the following code will be 1 and 0 respectively:

Let and const keywords

The let and const keywords solve these problems by providing block scoping for the variables, and do not support hoisting. Block scoping means that the scope of a variable is restricted to the scope in which it is declared, which is normally defined by curly braces. So, if a variable is defined inside a loop or an if condition, that variable is not available outside this block, as seen in the following example. Line 6 throws an exception of x is not defined, but we do get the correct response of 10 on line 4:

This helps reduce errors in code because we make sure we are using the variables in the correct scope. Also, the let keyword does not support hoisting, which means that variables are not moved to the top at runtime. They are accessible only after they are declared.

The const keyword is another way to declare variables and follows the same scoping principles as the let keyword. The only difference between const and let is that the values declared with const cannot change once they are bound. So, if you know that the variable you are declaring cannot and should not be allowed to reassign, then declare it with const, else use the let keyword.

Types in TypeScript

The JavaScript language does not have a concept of explicitly defining types of variables which end up being one of the main reasons for errors at runtime. We can assign one type to a variable and then later assign a different type to the same variable. TypeScript, with its type annotation, allows us to assign types to each variable, function, object, or class. Types act as a contract, which that variable has to follow, and the TypeScript compiler makes sure that there are no deviations from this contract. TypeScript does this with static and dynamic type checking. Types provide a set of rules which the compiler needs to follow for that variable; these rules also allow an autosuggest feature in IDEs by providing the most relevant options available. For example, by having types, we can make sure that while calling a function, we are passing the right set of variables.

TypeScript is an optional statically typed language, which means that it is not mandatory to assign types to each variable or function. This is why every JavaScript code is a valid TypeScript code. TypeScript provides a way to infer types for the variable based on the value assigned to the variable or the code flow. TypeScript will try to infer the best possible type, and then have checks in place to make sure that all the further operations do not contradict with the type. TypeScript also provides an option to explicitly opt out of the type for a variable by assigning the any keyword. For a variable with type any, TypeScript does not perform any type checking. This feature allows us to have existing JavaScript migrated to TypeScript without any issues.

TypeScript emits JavaScript even if there are type errors at compile time, allowing us to progressively update the JavaScript code. 

Type annotation

To specify a type to a variable or a function, TypeScript provides a syntax for defining a type preceded by a colon. Type annotation comes after the variable identifier. Types can be primitive types, or arrays, or complex types using classes and interfaces. The following example shows the basic syntax of defining types of variables and functions:

let num: number42;function example(name: string, age:number): number{return42;}

In the first line, when defining a num variable, it's optional to assign a value as well. In the function example, we see that we can define the type of the input parameter, and also for the return value. This helps us in making sure that all function calls are maintaining the correct signature contract.

Primitive types

TypeScript primitive types relate very closely to the types in JavaScript and follow the same principles. The primitive types available in TypeScript are as follows.

Number

A number data type can contain a double precision 64-bit floating point value. In TypeScript, the number has the same meaning as in JavaScript and represents all numbers, including decimals and hexadecimal. The following is an example of a number variable:

let num:number 42;let decimal 42.0;

String

The string data type represents textual data in UTF-16 format. To assign a string value to a variable, we use single (') or double (") quotes. We can also create a string that spans multiple lines, and is called a template string. The following is an example of declaring strings:

let firstName: string 'John';let templateHTML: string `<h1>Title</h1>`

In the preceding code, templateHTML is an example of using a template string. This is one of the features that is very frequently used in Angular to define inline templates for its components. We will see these when we start working on our application.

The strings also have an ability to add dynamic expression in its definition, as shown in the following example. The result variable will be Top 10 news feed from ESPN:

let news: string "ESPN";let count: number 10;let result: string `Top ${count} news feed from ${news}.`console.log(result);

The preceding code, when transpiled to JavaScript, produces the following output:

var news "ESPN";var count 10;var result "Top "+ count +" news feed from "+ news +".";console.log(result);

Tuples

Tuples can be seen as an advanced type of an array wherein we can have an array with elements not of the same type. For example, we can have any tuple that will have the first element of type string and the second element as a number, as shown here:

let details:[string, number];details ['John', 42];

The preceding code allows us to manage different data types in a single structure, which provides flexibility. 

Void

The void keyword is used to represent a scenario where there is no type. This is useful in the case of functions that do not return any value. These functions are annotated with void as a return type. In the following example, the doSomething function does not return any value, and hence has avoidas return type:

function doSomething(num: number):void{ console.log(num);}

Null and undefined

The null and undefined types are special types that can be assigned to any variable. They are not very useful on their own, as seen in the following example:

let value null;value 42;

Here, the value variable is of the any type, because null is a subtype of all the types and the compiler assigns any to the variable.

Union types

Most of the time, we are aware of what type of data a specific variable can hold, and we can annotate the said variable with that type. This helps in type checking at compile time, and makes sure we don't misuse the variable. But there are times when a variable may not be confined to one specific type, but can have multiple types of values. This is common in scenarios where we are migrating JavaScript code, or using reference of JavaScript libraries. 

TypeScript has the union type to solve this problem. A union type allows us to define a variable with multiple types; for example, a variable can have number and string types. This is achieved by using the pipe (|)symbol between the types, as shown here:

let

data

:

string

|

number;

data

10

;

data

'John'

;

Here, the data variable can hold both number and string, which allows us to have the flexibility to use both data types. The TypeScript compiler makes sure that it alerts us if we try to assign a type of value that was not defined.

Like union types, we have intersection types, which allow us to combine multiple types into one type. This is mostly used when we are using classes and interfaces for type declaration, hence we will look into this type when we discuss interfaces in the subsequent chapter.

Type inference

As we discussed in the Types in TypeScript section, TypeScript is an optional statically typed language, which means that TypeScript does provide types, but explicitly assigning types to variables is optional. TypeScript has an ability to infer types if not declared. Let's look at an example:

letfirstName"John";firstName10;

In the line firstName = 10, the compiler alerts us with the error that the variable firstName is a string, and a number cannot be assigned to a string. How does TypeScript identity this mismatch? TypeScript uses type inference to identify the type for the firstName variable.

In this case, TypeScript identified based on the assignment of the value at the time of variable declaration. If we had not assigned "John" to the firstName variable, the type inferred by TypeScript would have been any, as in the example shown here:

letlastName;lastName10;lastName'jj';

This is called type inference through declaration. Another place where you can see type inference in action is the return type of a function. TypeScript looks at the code and, based on the code flow path, decides the best suitable type. The following is one such example:

functiondoSomething(num:number){ return"name";}

In this case, TypeScript infers the return type as the string. Type inference is very useful in cases when we are working on legacy code of JavaScript; TypeScript will make sure to infer types for variables and functions based on the code flow.

Type checking

Once TypeScript has identified the types, it uses these for type checking in the program. TypeScript checks if we try to assign a type of value to a variable that contradicts the type defined for that variable, or when a function is called, TypeScript checks if we are passing correct types for the parameters and the return value is being assigned to the correct type of variable. The only exception to this type checking is the any keyword. If a variable or property is defined with the any keyword, the TypeScript compiler does not perform type checking for that variable.

Take a look at the following example of type checking:

letage:number;age=10;age"42"; //Compile Error: string can not be assigned to a number

In the preceding example, the TypeScript compiler alerts us on the last line with the message that 42 can not be assigned to a number, because although we are passing a number, we are passing it as the string. TypeScript, unlike JavaScript, does not coerce the types. TypeScript not only does type checking for primitive types, but also for arrays and custom types such as classes. We will look at an example of classes in the next chapter.

Apart from the types we have discussed in the preceding sections, there are other types in TypeScript as well, such as enum, generics, intersection types, and optional types. We will be looking into these types as and when we use them in our example application.

Classes in TypeScript

If we are developing any application using TypeScript, be it a small-scale or a large-scale application, we will use classes to manage our properties and methods. Prior to ES 2015, JavaScript did not have the concept of classes, and we used functions to create class-like behavior. TypeScript introduced classes as part of its initial release, and now we have classes in ES6 as well. The behavior of classes in TypeScript and JavaScript ES6 closely relates to the behavior of any object-oriented language that you might have worked on, such as Java or C#.

Object-oriented programming in TypeScript

Object-oriented programming allows us to represent our code in the form of objects, which themselves are instances of classes holding properties and methods. Classes form the container of related properties and their behavior. Modeling our code in the form of classes allows us to achieve various features of object-oriented programming, which helps us write more intuitive, reusable, and robust code. Features such as encapsulation, polymorphism, and inheritance are the result of implementing classes.

TypeScript, with its implementation of classes and interfaces, allows us to write code in an object-oriented fashion. This allows developers coming from traditional languages, such as Java and C#, feel right at home when learning TypeScript.

Access modifiers

Once the object is created, we can access the public members of the class with the dot operator. Note that we cannot access the author property with the espn object because this property is defined as private. TypeScript provides three types of access modifiers.

Public

Any property defined with the public keyword will be freely accessible outside the class. As we saw in the previous example, all the variables marked with the publickeyword were available outside the class in an object. Note that TypeScript assignspublicas a default access modifier if we do not assign any explicitly. This is because the default JavaScript behavior is to have everything public.

Private

When a property is marked as private, it cannot be accessed outside of the class. The scope of a private variable is only inside the class when using TypeScript. In JavaScript, as we do not have access modifiers, private members are treated similarly to public members.

Protected

The protected keyword behaves similarly to private, with the exception that protected variables can be accessed in the derived classes. The following is one such example:

class

base{

protected

id

:

number;

}

class

child

extends

base{

name

:

string;

details()

:

string{

return

`

${

name

}

has id:

${this

.id

}

`

}

}

In the preceding code, we extend the child class with the base class, and have access to the id property inside the child class. If we create an object of the child class, we will still not have access to the id property outside.

Readonly

As the name suggests, a property with a readonly access modifier cannot be modified after the value has been assigned to it. The value assigned to a readonly property can only happen at the time of variable declaration or in the constructor. We will look at constructors in Chapter 3, Sports News Combinator – Adding Features; here, we will see an example of a readonly property when initialized at the time of declaration:

 

In the above code, line 5 gives an error stating that property name is readonly, and cannot be an assigned value.

Transpiled JavaScript from classes

While learning TypeScript, it is important to remember that TypeScript is a superset of JavaScript, and not a new language on its own. Browsers can only understand JavaScript, so it is important for us to understand the JavaScript that is transpiled by TypeScript. TypeScript provides an option to generate JavaScript based on the ECMA standards. You can configure TypeScript to transpile into ES5 or ES6 (ES 2015) and even ES3 JavaScript by using the flag target in the tsconfig.json file. We discussed this setting in Chapter 1, Getting Started with TypeScript. The biggest difference between ES5 and ES6 is with regard to the classes, let, and const keywords which were introduced in ES6.

Even though ES6 has been around for more than a year, most browsers still do not have full support for ES6. So, if you are creating an application that would target older browsers as well, consider having the target as ES5.

So, the JavaScript that's generated will be different based on the target setting. Here, we will take an example of class in TypeScript and generate JavaScript for both ES5 and ES6. The following is the class definition in TypeScript:

This is the same code that we saw when we introduced classes in the Understanding Classes section. Here, we have a class named News that has three members, two of which are public and one private. The News class also has a format method, which returns a string concatenated from the member variables.

Then, we create an object of the News class in line 10 and assign values to public properties. In the last line, we call the format method to print the result.

Now let's look at the JavaScript transpiled by TypeScript compiler for this class.

ES6 JavaScript