Learn TypeScript 3 by Building Web Applications - Sebastien Dubois - E-Book

Learn TypeScript 3 by Building Web Applications E-Book

Sebastien Dubois

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

Learn TypeScript and many of its features by building state of art web applications from scratch with the help of modern tooling, frameworks, and libraries

Key Features

  • Create modern Web applications to help businesses around the world benefit from better quality applications
  • Learn the latest features of TypeScript 3 and use them wisely
  • Explore TDD practices, OOP techniques, and industry best practices to create high-quality and modular apps

Book Description

TypeScript is a superset of the JavaScript programming language, giving developers a tool to help them write faster, cleaner JavaScript. With the help of its powerful static type system and other powerful tools and techniques it allows developers to write modern JavaScript applications.

This book is a practical guide to learn the TypeScript programming language. It covers from the very basics to the more advanced concepts, while explaining many design patterns, techniques, frameworks, libraries and tools along the way. You will also learn a ton about modern web frameworks like Angular, Vue.js and React, and you will build cool web applications using those. This book also covers modern front-end development tooling such as Node.js, npm, yarn, Webpack, Parcel, Jest, and many others. Throughout the book, you will also discover and make use of the most recent additions of the language introduced by TypeScript 3 such as new types enforcing explicit checks, flexible and scalable ways of project structuring, and many more breaking changes.

By the end of this book, you will be ready to use TypeScript in your own projects and will also have a concrete view of the current frontend software development landscape.

What you will learn

  • Understand and take advantage of TypeScript's powerful Type System
  • Grasp the key concepts and features of Angular, React, Vue.js, and NestJS
  • Handle asynchronous processes using Promises, async/await, Fetch, RxJS, and more
  • Delve into REST, GraphQL and create APIs using Apollo
  • Discover testing concepts, techniques, and tools like TDD, BDD, E2E, Jest
  • Learn Object-Oriented and Functional Programming concepts and leverage those with TypeScript
  • Explore design practices and patterns such as SOLID, MVC, DI and IoC, LoD, AOP, and more

Who this book is for

This book is for software developers who are willing to discover what TypeScript is and how to leverage it to write great quality software. Developers that are already familiar with TypeScript will find this book useful by learning the languages featured introduced by most recent releases. Basic knowledge of the JavaScript programming is expected.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 842

Veröffentlichungsjahr: 2019

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.



Learn TypeScript 3 by Building Web Applications
Gain a solid understanding of TypeScript, Angular, Vue, React, and NestJS
Sebastien Dubois
Alexis Georges
BIRMINGHAM - MUMBAI

Learn TypeScript 3 by Building Web Applications

Copyright © 2019 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 authors, 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: Aaron LazarAcquisition Editor:Alok DhuriContent Development Editor:Pathikrit RoySenior Editor: Afshaan KhanTechnical Editor: Gaurav GalaCopy Editor:Safis EditingProject Coordinator:Francy PuthiryProofreader: Safis EditingIndexer: Manju ArasanProduction Designer:Arvindkumar Gupta

First published: November 2019

Production reference: 1221119

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

ISBN 978-1-78961-586-9

www.packtpub.com

To my beloved family, who have supported me more than I could ever hope for. I couldn't have made it without them!
– Sebastien Dubois
To my girlfriend, who has supported me during this challenge.
– Alexis Georges

Packt.com

Subscribe to our online digital library for full access to over 7,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.

Why subscribe?

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

Fully searchable for easy access to vital information

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

Foreword

TypeScript was unleashed into the world on October 1, 2012. At the time of writing, that makes it 7 years old. I was fortunate enough at that time to be allowed to use it from the get-go and spend time helping others with it via Stack Overflow. Sebastien has been part of the TypeScript journey with me since before it was popular. It was only later (circa 2016) that TypeScript blew up in popularity and now, in 2019, it is quickly becoming the de facto way to create web applications. Two key popular web UI frameworks, Angular and Vue, are both being written in TypeScript. The React team keeps a close eye on TypeScript, ensuring that new APIs are typesafe and that the TypeScript team supports React and JSX out of the box.That brings us to this book. There are few books out there that tackle the topic of building web applications with TypeScript head-on in the way that Sebastien's book does. One of the great things about this book is the expansive coverage of the best of what the JavaScript and TypeScript ecosystem has to offer. All major UI frameworks (React, Angular, and Vue) are covered. My personal recommendation of unit test framework (Jest) is in there. And even the backend portion of the ecosystems (GraphQL, Apollo, and Nest) is covered, providing a full picture on how to create modern web applications. In all honesty, I cannot think of a better resource that provides such a complete picture for developing web applications today with TypeScript in one place. And what better author than Sebastien, someone who has been such a helpful part of the TypeScript community.

Basarat Ali Syed

Basarat is a Microsoft MVP for TypeScript, an OSS fanatic, a book author, an egghead, and a Youtuber. He is a top contributor for TypeScript on Stack Overflow and, by day, he is a frontend practice lead. Find out more at http://basarat.com.

Contributors

About the authors

Sebastien Dubois is a passionate software craftsman and FOSS contributor with many years of experience as a senior developer and technical team leader.

He isan entrepreneur, IT consultant/coach, and owner of DeveloPassion, aBelgianIT firm.

Over the years, Sebastien has worked on backend systems, web applications, architecture, and IT security forvariousorganizations.He has used different programming languages, which gives him a broad perspective on modern software development.He hasalsobeen using, teaching, and advocating TypeScript since 2015.

You can find him on Twitter as @dSebastien, on Medium as @dSebastien, or on his personal blog: dsebastien.

Alexis Georges is a developer who is passionate about software development, but also about everything related to IT: open source, system administration, respect for privacy, and many others.

During his studies in programming and networking, he learned the basics of programming and system administration.

Alexis has some experience in JavaScript, PHP, Java, C, and (obviously) TypeScript. He discovered the TypeScript programming language when he began his career as a software engineer in Sebastien's team. Later, he participated in the migration of the Stark framework from AngularJS to Angular.

You can find him on Twitter as@Super_ITMan and on his blog: SuperITMan.

About the reviewers

Christopher Allán Cortés Ruiz is a skilled developer and experienced frontend architect with a deep knowledge of JavaScript and TypeScript. He can grasp their new features rapidly to get the most out of them. He has mastered several of the latest frontend technologies, such as AngularJS, Angular, Redux, and NPM, which he has used in several recent projects. Moreover, he has made an outstanding contribution to advertising and financial companies in Mexico, Spain, and Belgium by revamping their frontend applications with the most cutting-edge standards and technologies, from contributing to architectural design and coaching junior developers, through putting in place solid and stable coding, right to the implementation of the user interface.

I want to thank Sebastien Dubois for allowing me to be part of his excellent book about TypeScript as a reviewer. I'm also grateful to my former colleagues, Jurgen and Hendrik, who have taught me a lot professionally and personally. Finally, I also want to thank my wife, Rosa, because without her patience and understanding, all those long nights of learning and reading about the latest technologies wouldn't have been so rewarding.

Martin Jurča works as a tech leader and developer for Seznam.cz. He is passionate about TypeScript, frontend technologies, and pushing the limits of what is possible. Martin was a reviewer of Hands-On RESTful APIs with TypeScript 3, gave a speech at JSConf Iceland, is a regular speaker at tech conferences in Brno, and is a regular tutor at the Seznam IT academy.

Martin likes to relax with a good book, a hike, or his friends over a bottle of wine or a cup of tea. He lives in Brno with his wife and baby daughter.

I would like to thank my amazing wife for all the support she gives me and for every day I get to spend with her. I would also like to thank my daughter for motivating me to be a better person every day.

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Learn TypeScript 3 by Building Web Applications

Dedication

About Packt

Why subscribe?

Foreword

Contributors

About the authors

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

Introduction to TypeScript

TypeScript in a few words

JavaScript

JavaScript's history in a nutshell

ECMAScript

ECMAScript evolution and support

JavaScript gotchas

How can TypeScript help?

Enhanced JavaScript

Future JavaScript today

Static typing

Structural typing

Types for JavaScript libraries

.NET and Java developers will feel at home

What you'll need to install

Text editor

Version control system

Shell

JavaScript runtime

Package manager

TypeScript

Installing VS Code

Windows

Windows (shell)

Linux (GUI)

Linux (shell)

Extensions

Installing and configuring Git

Windows

Linux (shell)

Configuring git

Downloading the book samples

Installing Node.js and npm

Windows

Git BASH

Linux (shell)

Updating npm

Linux

Windows

Installing TypeScript

Hello world with TypeScript

Creating the project

Hello (Type/Java)Script!

Compiling manually using the TypeScript compiler

Variables declaration

Basic TypeScript types

A tiny bit of type safety can't hurt

Summary

Further reading about ECMAScript

Building TodoIt - Your Own Web Application with TypeScript

What will you build?

Creating the project using npm

Introducing npm

package.json

Installing dependencies with npm

Installing dependencies with npm and package.json

The node_modules folder content

Updating dependencies with npm

package-lock.json

Defining and executing npm scripts

When not to install packages globally

Adding TypeScript to the project

Configuring the TypeScript compiler

Creating the TodoIt application

Opening the project in VS Code

Defining the basic application structure

Leveraging VS Code support for TypeScript

Building from the Terminal

Using Browsersync to refresh automatically

Implementing the user interface

Loading the TodoIt code and checking the browser console

Creating the todo list with TypeScript arrays

Getting hold of inputs and casting using the as operator

Adding todo items to the list

Listing existing todo items using lambda expressions

Listing existing todo items using loops

Filtering existing todo items using the ES2015 TypeScript support

Removing a single todo item

Debugging your code in the web browser

Debugging your code in VS Code

Generating source maps for easier debugging

Summary

Improving TodoIt with Classes and Interfaces

About programming paradigms

Basic OOP principles and nomenclature

Encapsulation and classes

Abstraction

Inheritance and abstract classes

Interfaces

Polymorphism

Composition

Composition over inheritance

Bonus: UML

Class diagrams

JavaScript and OOP

Overview of the TypeScript support for OOP

TypeScript classes

Basics

Bonus: How TypeScript converts classes to JavaScript

Fields, methods, visibility, and constructors

Inheritance

Fluent APIs

Custom types

Inline types

Type aliases

TypeScript interfaces

Defining contracts

Naming custom types using interfaces

Extending interfaces

Interfaces only exist at compile time

Interfaces versus type aliases and inline types

Interfaces versus classes

Starting point

Designing the domain model of TodoIt v2

First proposal

Single responsibility principle (SRP)

Law of Demeter (LoD)

Open/closed principle

Using the Model View Controller (MVC) design pattern

Implementing the new domain model

Creating the TodoItem class

Creating the TodoList class

A note about TypeScript's ReadonlyArray

Implementing the view

Creating the TodoListView interface

Implementing the TodoListView interface

Implementing the controller layer

Creating the TodoListController interface

Implementing the TodoIt controller class

Initializing TodoIt

Isolating the utility function

Updating the HTML page

Job done, congratulations!

Summary

Leveraging Generics and Enums

What will you build?

Generics

The benefits of using generics

An example without generics

An example with generics

An example with generic functions and interfaces

An example with classes

Generic constraints

Enums

Numerical enums

String enums

const enums

The never keyword

String literal types

Union and intersection types

Type guards

The typeof keyword

The instanceof keyword and the Visitor pattern

User-defined type guards and the is operator

And more on type guards

Creating the project

Designing the model

The core domain model

High-level design – first proposal

The service layer design pattern

High-level design – second proposal

Implementing the domain model

Defining the media service interface

Storing data on the client side

LocalStorage and SessionStorage

IndexedDB

Implementing the media service

Library choice

Introduction to the Promise API

TypeScript type definitions (typings)

Adding localForage to the project

Service implementation

Handling serialization/deserialization

Installing class-transformer and reflect-metadata

Adding class-transformer decorators to domain classes

Implementing the saveMediaCollection method

Implementing the loadMediaCollection method

Implementing the getMediaCollectionIdentifiersList method

Implementing the removeMediaCollection method

Implementing the view

CSS

HTML page

Defining the view interface

Implementing the HTMLMediaManView class

The base structure

Implementing basic validation using the HTML Form Validation API

Why exceptions should not be used in this case

Implementing the clearBookCollections method

Implementing the displayErrorMessage method

Implementing the renderBookCollection method

Implementing the clearNewBookCollectionForm method

Implementing the renderBook method

Implementing the removeBookCollection method

Implementing the getNewBookDetails method using keyof and typeof

Bonus – the keyof operator

Bonus – mapped types

Implementing the clearNewBookForm method

Implementing the removeBook method

Creating the controller layer

Defining the interface

Implementing the MediaManController class

Implementing the reloadBookCollections method

Implementing the createBookCollection method

Implementing the removeBookCollection method

Implementing the createBook method

Implementing the removeBook method

Initializing the application

Summary

Coding WorldExplorer to Explore the Population of the World

Understanding modules

Why do we need modules?

A bit of history about JavaScript modules

The Revealing Module pattern

The AMD and CommonJS modules

UMD modules

ES modules

Loading and bundling modules

Module loaders

Bundlers

Exploring TypeScript modules

Export and import syntax

Export statements

Re-exports and barrels

Barrels

Bonus: Leveraging modules in MediaMan

Ambient modules

Configuring module transpilation

Advanced concepts

Namespaces

Introducing module resolution

Resolution strategies

Resolving relative imports

Resolving non-relative imports

Configuring module resolution

What will you build?

Bonus: REST, RESTful and web APIs

World Bank Open Data APIs

Country information

Indicators

Population information

Understanding the Fetch API

Using the unknown keyword

Chaining promises

Understanding async/await and generators

Asynchronous code that looks synchronous

Compatibility

Adding runtime type checks

TypeScript non-goals

Use cases

io-ts

io-ts examples

Creating the project

What's inside of the project skeleton?

Designing the model

Core domain

Implementing the domain model

Implementing the population service

Defining the contract

Creating the service implementation skeleton

Implementing the getAllCountries method

Implementing the getCountry method

Implementing the getTotalPopulation method

Implementing the other methods

Creating the service layer barrel

High-level design

The controller package

The view package

Implementing the view layer

HTML template

Creating the view package

Implementing the view model using a Data Transfer Object (DTO)

Defining the view contract

Installing Chart.js

Creating the view implementation skeleton

Implementing the displayCountries method

Implementing the displayYears method

Implementing getChartFormDetails and using the property shorthand notation

Implementing the displayChart method

Creating the view layer barrel

Implementing the controller layer

Creating the controllers package

Defining the controller contract

Creating the controller implementation skeleton

Implementing the loadCountries method

Implementing the loadYears method with generators

Implementing the renderChart method

Implementing the UnreachableCaseError class

Creating the controller layer barrel

Initializing our application

Leveraging TypeScript path mappings

Summary

Further reading

Modules

Namespaces

RESTful APIs

The Fetch API

Async and await

io-ts and fp-ts

Generators

Introduction to Testing

Introducing testing

Code quality and testing

Test types

Functional tests

Non-functional tests

Testing approach and mindset

Mocks and stubs

The test pyramid

Test automation and the Definition of Done (DoD)

Test Driven Development

Behavior Driven Development

JavaScript testing libraries and tools

Unit testing

E2E testing and other tools

Testing the population service of WorldExplorer

Installing and configuring Jest

Using npm script hooks

Writing basic tests

Testing asynchronous code

Implementing positive and negative tests for getAllCountries

Spying on methods with Jest

Summary

Discovering Angular, Angular Material, and RxJS

Learning about modern web applications

Server-side rendering

SPAs

Mobile-first and responsive web design (RWD)

PWAs

Modern web frameworks

Understanding TypeScript decorators

What are decorators?

When are decorators useful?

Aspect-Oriented Programming

Exploring Angular

What is Angular?

Model View Whatever (MV*)

Angular CLI

Bonus: Schematics

Bonus: Hello world with the Angular CLI

Learning the Angular application architecture

Exploring core Angular concepts

Modules

Components

Component templates and data bindings

Component bindings, HTML attributes, and DOM properties

Defining component inputs and outputs

Smart versus dumb components

Component life cycle hooks

Routing

Directives

Pipes

Change detection

Services

DI

Learning about injectors and the singleton design pattern

A brief note about the root application injector

Angular's bootstrap process

Angular workspaces and the angular.json file

Angular testing support and coverage reports

Angular testing utilities

Bonus: Angular Console

Bonus: Augury

Introducing RP and RxJS

RP libraries

RxJS basics − observables

RxJS basics − observers

RxJS basics − subscriptions

RxJS basics − subjects

RxJS basics − hot and cold observables

RxJS basics − operators and marble diagrams

Exploring Angular forms

Template-based forms

Reactive forms

Introducing Material Design and Angular Material

Summary

Further reading

PWAs

TypeScript decorators

RP and RxJS

Angular

CLI

Router

Modules

Life cycle hooks

Directives

Components

Pipes

Services

DI

Change detection

Forms

Miscellaneous

Rewriting MediaMan Using Angular and Angular Material

What will you build?

Creating the project

Creating the project using the CLI

Reviewing the application structure

Extending another TypeScript configuration

Folder structure and the LIFT principle

Adding required dependencies

Starting the development server

Defining the application title

Integrating the shared logic

Implementing the book module

Creating the module

Implementing the bookCollection methods

Implementing the book method

Creating the book page component

Adapting the book module

Importing the book module

Migrating the styles

Implementing book creation

Displaying book collections

Adding the components to the page

Revisiting the user interface with Angular Material

Installing Angular Material

Adding a toolbar

Making the application responsive

Revisiting the book page

Improving the book creation component

Improving the book list component

Cleaning things up

Summary

Introducing Vue.js

Vue.js

Hello Vue!

Understanding Vue concepts

Directives

Components and props

Component prop types and validation rules

The internal state of a component

Listening to events that have been triggered by child components

Single File Components (SFCs)

Similarities with Angular

Computed properties

Watchers

Filters

Lifecycle hooks

Mixins and pure functions

Render functions

Testing support

Vue developer tools

The Vue CLI

Bonus – creating a new project using the Vue CLI

TypeScript support

Compiler configuration

SFC with vue-class-component

Splitting components into multiple files

Dependency injection

Built-in support

TypeScript support

Limitations

Improving our code with ES2015 symbols

Late binding and TypeScript definite assignment assertions

The SL design pattern and InversifyJS

SL using InversifyJS and reflect-metadata

Better InversifyJS integration

User interface component libraries

Vuetify

Buefy

Quasar

Element

And many others

Routing

State management for modern web applications

Naive approach – propagating state changes using custom events and props

Broadcasting state changes

Simple store pattern

Redux and the unidirectional data flow

A note about pure functions

VueX

Summary

Further reading

Vue

General

Components

Computed properties

Filters

Mixins

Render functions

Testing support

Router

VueX

TypeScript

Symbols

Creating LyricsFinder with Vue.js

What will you build?

High-level design and technical stack

Schema

Music service

User interface

TypeScript

Getting started

Creating the project

Starting the development server

Project structure and conventions

Getting a MusixMatch API key

Configuring InversifyJS

Creating the home view

Creating the skeleton

Installing and configuring Vue Router

Installing and configuring Element

Implementing the basic layout of the application

Creating the search component and using Vue slots

Handling search using the MusicService

Creating and using the songs list component

Creating and using the lyrics view

Summary

Further reading

Diving into React, NestJS, GraphQL, and Apollo

Introducing React

History

Application architecture

Numbers, numbers, numbers

Evolution and support

Understanding JSX

Introduction

JSX is not HTML

Expressions

Attributes

Element trees

React elements

Components and props

Class components

Function components

Object destructuring

Component state

Bonus: Improving rendering performance

Lifecycle hooks

Emitting and handling events

Communication between distant components

Controlling rendering

Rendering lists

Content projection/templating

Exploring React hooks

Defining state with the useState hook

Array destructuring

Handling side-effects with the useEffect hook

The React developer tools

Taking advantage of the Create React App (CRA) tool

Creating a project using create-react-app

File and folder structure

Generating a TypeScript project

Leveraging TypeScript with React

JSX support through TSX files

Class components with TypeScript

Class components with internal state

Types provided by React typings

Class components accepting props

Functional Components with TypeScript

Introducing the prop-types library

Going further with Functional Components

Discovering NestJS in a jiffy

Architecture

CLI

Modules

Dependency injection

Controllers and routing

And everything else

Introducing GraphQL

Introduction

Queries

Schema, validation, and resolvers

Apollo

The NestJS GraphQL plugin

Summary

Further reading

React

General

JSX

CreateElement

Components

Function components

State management

Component lifecycle

Context

Hooks

Create React App

TypeScript and React

NestJS

GraphQL

Apollo

NestJS support for GraphQL

TypeScript

Object destructuring

Array destructuring

Revisiting LyricsFinder

What will you build?

High-level design and technical stack

Schema

Frontend – user interface with React Bootstrap

Frontend – API calls

Backend

TypeScript

Getting started

Creating the project

Project structure and conventions

Backend – creating and configuring the application

Starting the development servers

Backend – adding the necessary dependencies

Backend – implementing the GraphQL API with a first resolver

Adding your MusixMatch API key

Creating the song module

Creating the song GraphQL resolver

Creating the song DTO and decorating it for GraphQL

Implementing the song resolver and leverage NestJS features

Backend – importing and configuring the GraphQL NestJS module

Backend – testing the API using the GraphQL playground

Backend – adding support for artists and lyrics

Frontend – installing React Bootstrap

Frontend – installing React Router

Frontend – creating the home view skeleton

Creating the lyrics view skeleton

Frontend – creating the search component

Creating the search component skeleton

Defining the component hierarchy

Adding state and binding our input to it

Clearing the input

Adding the search handler

Adding props to communicate with the outside world

Frontend – integrating with the backend API

Adding the required dependencies

Defining GraphQL queries and generating code using Apollo

Bonus: Tagged template literals

Creating, configuring, and using an Apollo GraphQL client

Frontend – creating and using the songs list component

Creating the skeleton

Defining the props

Rendering the list of songs

Frontend – loading lyrics and redirecting to the lyrics page

Frontend – implementing the lyrics page

Adding icons

Creating an ArtistsList component

Showing a message when there are no songs or no artists

Adding loading indicators

Summary

What's Next?

Retrospective – first half

Retrospective – second half

Where to go next and what to learn

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Dear reader,

Thank you for joining us on this learning journey!

As we will discover together throughout the book, the TypeScript programming language can be used to write awesome applications and greatly enhance the developer experience and code quality/safety. TypeScript can be used wherever JavaScript can be, which means practically everywhere.Moreover, TypeScript works wonderfully well with all major libraries and frameworks. Last but not least, it also has a large, vibrant, and enthusiastic community.

With this book, our hope is that we will be able to convince you that TypeScript is a great programming language and that it is relevant whether you are writing frontend applications, backend systems – or whatever else, actually.

Throughout the book, we will give you everything you need in order to acquire a good understanding of how powerful TypeScript really is, how versatile it can be, and how it fits into the modern development puzzle.

But don't take our word for it – we'll show you!

This is a practical book, not a reference guide. We will hold your hand through the journey, but you'll have to roll up your sleeves and get your hands dirty. We strongly believe that learning by doing is the most time-efficient approach to mastering new subjects and this is exactly why we have created this book regarding the TypeScript programming language. In addition, we also love to share our passion for technology and we really hope that you'll enjoy reading this book.

In the first half, we will introduce you to many important features of the TypeScript programming language through exercises and by helping you to create multiple applications. While creating those first applications, you will also learn about many important APIs of the modern web as well as many useful design patterns, techniques, libraries, and tools.

By reading through the chapters and, most importantly, by coding these applications, you'll gain a really good understanding of how TypeScript works and how it fits into the modern software ecosystem.

In the second half of the book, we will continue to teach you about TypeScript features, but our focus will shift to discovering how TypeScript can be combined with some of the most popular libraries and frameworks out there today: Angular, Vue.js, and React. Not only that, but we will also show you how to write backend applications using NestJS, GraphQL, and Apollo.

All of those frameworks and libraries will be explained in the book in enough detail to give you a real taste of how they actually work and without requiring you to do a lot of side research. You'll go from zero to hero in no time!

This book is truly unique; you won't find many others covering so many subjects in a simple, approachable, and cohesive way. Step by step, you'll go from the basics to the more advanced concepts and you'll create cool applications along the way!

Who this book is for

This book is for software developers looking to discover the following:

What TypeScript is

What TypeScript brings to the table

Why TypeScript adds value for both small and large software development teams

How to leverage TypeScript to write great quality software

This book is also relevant for developers already familiar with TypeScript who wish to know how the language has evolved over time or get a refresh, including what has been introduced by the most recent releases and how best to leverage the language with various modern web frameworks.

In any case, this book is for developers who want to learn by doing rather than by reading a thousand pages of language specifications. This book is also relevant/useful for both backend and frontend software engineers.

What this book covers

Chapter 1, Introduction to TypeScript, presents the current frontend development landscape and explains why TypeScript comes into the picture. It illustrates the problems of vanilla JavaScript and goes on to present TypeScript and show how it can improve code quality, improve the developer's life, and help larger teams. Then, it shows you how to install everything you'll need to work on the projects covered in the book.

Chapter 2, Building TodoIt – Your Own Todo Management Web Application with TypeScript, guides you in building a first concrete project using TypeScript: a simple todo management web application. This application will make use of npm, TypeScript, HTML, and a bit of CSS for good measure. This project is a great introduction to the TypeScript language, tsc (the TypeScript compiler), its configuration file (tsconfig.json), npm, and some other valuable tools. By going through this chapter, you will learn about TypeScript basics by creating some TypeScript files, defining variables of different (basic) types, functions, and compiling code before checking the results.

Chapter 3, Improving TodoIt with Classes and Interfaces, revisits the TodoIt application by making use of classes and interfaces. This will drastically improve code quality by going from a purely imperative programming approach to a more object-oriented one. This will help code convey more meaning and isolate concerns more properly. This chapter covers Object-Oriented Programming (OOP) basic concepts and nomenclature: encapsulation, abstraction, inheritance, polymorphism, interfaces and classes, composition over inheritance, and more. The chapter then helps you define the domain model of the application using Unified Modeling Language (UML). That model is then implemented using TypeScript. While doing so, you will create some classes, and you will discover how to define constructors, how to set default values, how to use accessors, and more. Inheritance will also be covered as well as interfaces. You will learn about structural typing as well as how TypeScript classes and interfaces, and JavaScript objects and classes, relate to one another.

Chapter 4, Leveraging Generics and Enums, guides you through building a media management web application. Along the way, you will learn about generics and enums and you will leverage them to write better code. The application's data will also be persisted in the web browser's local storage, which will teach you about its existence and the corresponding APIs used to store/retrieve data from local storage. While implementing the application, you will discover how to use third-party libraries with TypeScript, what type definitions are, and how to retrieve them.

Chapter 5, Coding WorldExplorer to Explore the Population of the World, helps you to create an application that gets data from a RESTful web API of the World Bank using the Fetch and Promise APIs available in all modern web browsers. With this project, you'll dive deeper into TypeScript concepts such as modules, module resolution, and barrels. You will also learn about using async and await to make asynchronous code look synchronous. While covering these subjects, we will take some time to discuss REST, RESTful, and web APIs. The project code will be organized so as to facilitate testing, which will again put emphasis on the importance of testing and good isolation between parts of the code base. Finally, the project will make use of Chart.js (https://www.chartjs.org/) to create interactive visualizations of the data. Again, this will familiarize you with the usage of third-party libraries in TypeScript.

Chapter 6, Introduction to Testing, covers some important ideas around code quality and software testing. The focus of the chapter will be on how to ensure that an application behaves in the intended manner, both from a functional and non-functional point of view. You'll discover, or re-discover, the different types of tests that can be written, the different testing techniques, and the tools of the trade in the JavaScript and TypeScript ecosystem. Finally, you will also learn how to write tests using the Jest (https://jestjs.io/) library.

Chapter 7, Discovering Angular, Angular Material, and RxJS, explains what modern web applications are all about. It then goes on to introduce the Angular (https://angular.io/) framework, as well as Material Design (https://material.io/design/) and Angular Material (https://material.angular.io/). In addition, it will also teach you about Reactive Programming and the RxJS (https://rxjs-dev.firebaseapp.com/) library.

Chapter 8, Rewriting MediaMan Using Angular and Angular Material, helps you to create your first Angular application using TypeScript, Angular Material, and RxJS.

Chapter 9, Introducing Vue.js, introduces Vue.js (https://vuejs.org/), its major concepts, as well as the surrounding tools (such as Vue CLI). This will provide you with a broader point of view as it shows a different and lighter way of creating modern web applications. While introducing Vue.js, we will also explain how to leverage TypeScript to write better code. This chapter also covers the dependency injection pattern and explains how to use InversifyJS (http://inversify.io/) to implement this pattern within Vue.js applications.

Chapter 10, Creating LyricsFinder with Vue.js, helps you create yet another application, this time using Vue.js, Vue CLI, and the Element (https://element.eleme.io/#/en-US) UI toolkit. This application will be more complex, as it will need to interact with multiple web APIs in order to fetch the required information. This will help us demonstrate how to properly handle asynchronous processing using modern libraries.

Chapter 11,Diving into React, NestJS, GraphQL, and Apollo, introduces one more way to create modern web applications, using React (https://reactjs.org/), a tremendously popular library. This chapter also introduces NestJS (https://nestjs.com/), a backend application framework, as well as GraphQL (https://graphql.org/) and Apollo (https://www.apollographql.com/), which can be leveraged to create modern APIs. Of course, you'll also see how to best leverage TypeScript with each of those!

Chapter 12,Revisiting LyricsFinder, revisits the LyricsFinder application using React and React Bootstrap (https://react-bootstrap.github.io/). In this chapter, you'll also build a backend application using the NestJS framework. On the backend side, you will create a simple GraphQL API using the Apollo framework. After completing this project, you will have seen three different approaches to create modern web applications and will have integrated multiple libraries, clearly showing the benefits and complexities that arise along the way. Also, you will have used TypeScript to implement a backend system using NestJS, a modern framework inspired by Angular.

What's Next?, concludes the book, but only marks the beginning of your own learning journey.

To get the most out of this book

Basic knowledge of the web platform, web browsers, HTML, and JavaScript is expected. Knowledge of CSS would be nice to have but is notmandatory. Basic familiarity with OOP concepts is also expected.

This book will introduce the most important concepts in any case to make sure that more beginner readers can follow along and gain additional knowledge.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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.packt.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 athttps://github.com/PacktPublishing/Learn-TypeScript-3-by-Building-Web-Applications. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781789615869_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.packt.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.

Reviews

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 packt.com.

Introduction to TypeScript

In this first chapter, we start by looking back in time in order to explain how the JavaScript language has evolved since its creation. This will help us to better understand why/where TypeScript comes into the picture.

We begin by illustrating the problems of vanilla JavaScript. Then, we will turn our attention to TypeScript.

This chapter also states how TypeScript can improve code quality and a developer's life, and help larger teams, by making it possible to create solid and easier-to-maintain code bases.

After that, we review some of the tools that you will need to work on the projects provided in the book and cover how to install each of them. This includes the code editor, the JavaScript runtime, the package manager, a source control management system, TypeScript, and more.

We will also see how to write the famous Hello World program with TypeScript and you'll learn a few things about variable declarations and basic TypeScript types.

In this chapter, we will cover the following topics:

Overview of the current frontend software development landscape

What is TypeScript and how does it help to improve code quality?

Similarities between .NET (C#), Java, and TypeScript

The minimum level of toolkit necessary for frontend development

How to install Visual Studio Code

How to install Git

How to install Node.js and

npm

How to update

npm

Where are

npm

packages installed?

How to install TypeScript

Introduction to basic TypeScript types (

boolean

,

number

,

string

, string literals)

Variable declarations:

var

versus

let

versus

const

Basic functions

How to write the

Hello World

program in TypeScript

TypeScript in a few words

The TypeScript programming language (http://www.typescriptlang.org) was created by Microsoft and was later open sourced under the Apache 2.0 license. The source code of the language is available on GitHub over at https://github.com/Microsoft/TypeScript. At the time of writing, TypeScript now has 51,705 stars and 7,116 forks on GitHub and its popularity continues to rise.

The first thing to realize is that TypeScript compiles to JavaScript. This means that the output of the TypeScript compiler can run wherever JavaScript code can run, which actually means, nowadays, basically everywhere, since JavaScript can run in the following:

Web browser

Backend (for example, with Node.js)

Desktop (for example, with Electron)

Mobile, with frameworks such as React Native, NativeScript, Ionic, and many others

The cloud, with platforms such as Azure Functions, Google Cloud Functions, and Firebase

As stated earlier, TypeScript is compiled and not interpreted like JavaScript is. Actually, people often talk about transpilation rather than compilation in the case of TypeScript, since the TypeScript compiler actually does source-to-source transformation.

The second key point is that TypeScript is a superset of JavaScript as shown in the following diagram:

This means that any valid JavaScript code is also valid TypeScript code. This is great because it means that it is very easy to introduce TypeScript into an existing JavaScript code base. It does not stop there, though! As you'll see throughout the book, TypeScript adds a lot over vanilla JavaScript.

A third takeaway is that TypeScript is (optionally) typed. If you're familiar with JavaScript, then you probably know that it is a dynamically and weakly typed language. As any JavaScript code is also valid TypeScript code, it also means that you can declare variables without specifying their type and later assign different types to them (for example, numbers, strings, and more).

Although the fact that defining types is optional by default in TypeScript does not mean that you should avoid defining types. Instead, TypeScript shines when you make clever use of its type system.

TypeScript allows you to clearly specify the type of your variables and functions. In addition, it also has very powerful type inference, support for classes, generics, enums, mixins, and many other cool things that we’ll see throughout the book.

We'll see later in the book how to configure the TypeScript compiler to be stricter and we'll also learn the benefits of enforcing and leveraging strong typing at work, as well as for personal projects.

This quick introduction to TypeScript is useful for you to grasp what it is, but it does not explain why it exists and why it makes sense for you to use it.

JavaScript

Before we begin our TypeScript journey, it is useful to take a look back at JavaScript and where it comes from.

JavaScript's history in a nutshell

Before we go any further, we should take some time to briefly discuss the history of JavaScript and how it has evolved in recent years. You probably know that JavaScript is the core language of the web. It's actually a very versatile language that supports different programming paradigms such as imperative, object-oriented, functional, and event-driven programming.

As mentioned in the previous section, JavaScript can now be used almost everywhere, but that was not always the case. The language was initially designed by Brendan Eich (https://brendaneich.com) around 1995 (more than 20 years ago!) for the Mosaic web browser. The first version of the language was written in 10 days (!) and was called Mocha, and was later renamed to LiveScript. The whole story is very interesting and well worth reading.

It is important to realize that JavaScript has been here for a very long time and has also evolved a lot, especially since 2005, and more than ever since 2015.

ECMAScript

Another important thing to understand is that behind JavaScript, there is actually a language specification called ECMAScript, standardized by Ecma International in ECMA-262 since 1996. Though reading about it will be time consuming for now and not mandatory in order to understand further topics, you should know that this specification governs what JavaScript is and how it evolves. New language features and API proposals all go through the Ecma TC39 technical committee, which decides which ones are mature enough to make it into the specification. This all happens in the open, so don't hesitate to go and check it out.

ECMAScript evolution and support

The version of JavaScript that most developers around the world are familiar with is ES5, which was released in 2009. It included strict mode, accessors, syntax changes, meta-programming, and, most importantly, support for JSON.

Since 2015, ECMAScript, and thus JavaScript, has rapidly evolved. The specification now has a yearly release schedule, meaning that a new version is released each year. Thanks to this evolution, each year, all of the language change proposals that are mature enough get included in the new version of the specification. This follows a trend that we can see throughout the industry to increase the pace at which things evolve. It is very disruptive for large enterprises but is great for innovation.

In 2015, ECMAScript 6 was released and was later renamed ES2015. Since then, ES2016, ES2017, ES2018, and ES2019 have been released in the respective years.

Note that ESNext will always refer to the next version with the proposals that have not been finalized yet.

Make sure to stop by Dr. Axel Rauschmayer's blog (http://2ality.com) to learn more. Comparatively, ES2015 was incredibly bigcompared to the following iterations.

As you can imagine, it takes time for browser vendors and JavaScript engine developers to integrate newly standardized elements of the language. With ES2015, this meant that things such as let, const, classes, and many other features could not be used directly. This led to the increase in popularity of transpilation using tools such as Babel or TypeScript. Basically, the idea is to be able to use the newest features of the specification in your code right now and to transpile it so that it can run in environments that don't support those features just yet.

How can TypeScript help?

Now that we've introduced TypeScript and have briefly covered JavaScript's history, evolution, and gotchas, we can finally discuss why TypeScript is relevant and why you should use it.

Enhanced JavaScript

First and foremost, TypeScript does not aim to replace JavaScript; instead, it aims to improve the lives of developers by providing a more powerful language that generates clean and simple JavaScript code. In a way, you could consider TypeScript as a code quality checker for JavaScript on steroids.

Future JavaScript today

A second big benefit is that TypeScript allows you to use the newest ECMAScript features right now, whether you're targeting the latest version of Node.js or Internet Explorer 11 (poor soul!). This is great because it means that you don't need to wait until everything is supported in the target environment.

You can very easily configure the TypeScript compiler to generate ES3-, ES5-, ES2015-, ES2016-, ES2017-, ES2018-, ES2019-, or ESNext-compatible code.

To make this clearer, let's take an example. In TypeScript, you can create classes while transpiling your code to ES3-compliant code, even though classes were only introduced in ES2015. The TypeScript compiler only performs transformations to use language constructs that existed in that version of ECMAScript. When TypeScript does this, we often talk about down-level emit. There are many features of most recent ECMAScript versions that you can use with TypeScript while targeting ES5.

Static typing

One of the best features of TypeScript is its powerful type system added on top of JavaScript. This alone should appeal to any developer who is used to working with strongly typed languages, and thus, used to benefiting from great IDE support.

When you develop using C# or Java with a solid editor/IDE, you get powerful auto-completion, refactoring support, access to the documentation, in-context hints, and warnings and errors, all for free. TypeScript provides the same developer experience for the JavaScript ecosystem and allows developers to benefit from a highly productive development environment. This is great for all developers, not only larger teams.

Whether you're a fan of static or dynamic typing, TypeScript will make you happy as types in TypeScript are optional and TypeScript has very powerful type inference capabilities. Moreover, type inference improves with each new release of the compiler.

Put simply TypeScript definitely will help you discover bugs earlier and it will help you to better organize and structure your code, whether you're working on a small application or a large project.

Structural typing

In TypeScript, usually, if things quack like ducks, then TypeScript assumes that they're ducks. Ducktyping as it is called is baked into the language. We can say that TypeScript considers the compatibility of types. We’ll leverage this great feature in the projects to make things clear.

To give you an idea, if some function expects to receive an object of a Foo type and is instead called with an object of a Bar type, then TypeScript will not complain as long as Bar has the same structure as Foo. That is to say, a Bar object can be considered to be Foo if it exposes at least the expected properties/methods.

This is an oversimplification as there are actually many rules at play, depending on the considered types.

Structural typing is very useful as it helps avoid writing quite some boilerplate code; one example is when you have two equivalent data structures. In programming languages that don't support structural typing, you have to manually convert from one type to the other, just because the compiler doesn't recognize the structural compatibility of the types.

TypeScript does also supports some nominal typing (that is, non-structural). Nominal typing is interesting for cases where you want to distinguish objects with different types, even if their structure is identical.

We won't be covering nominal typing specifically in this book as it is more advanced, but do check out the following link if you're curious: https://basarat.gitbooks.io/typescript/docs/tips/nominalTyping.html.

Types for JavaScript libraries

Having auto-completion and type information for third-party libraries that you use is a huge time saver and it can also help you avoid many bugs. Now, you might wonder how TypeScript can provide you with type information for third-party libraries when they are not written themselves in TypeScript. Well, the TypeScript team and the community have got you covered!

TypeScript supports type definitions, also known as typings. Type definitions are sets of declarations that provide additional information to the compiler (somewhat similar to header files in C). You'll discover how this works while working on the projects of this book.

Type definitions are maintained for most major libraries and are maintained either by the community or the library developers themselves. In most cases, typings are available on DefinitelyTyped, a community-driven repository of type definitions available on GitHub, over at https://github.com/DefinitelyTyped/DefinitelyTyped.

In the following article, you can find the history of DefinitelyTyped, explaining how it came to be and how it has evolved to become so central in the TypeScript ecosystem: https://blog.johnnyreilly.com/2019/10/definitely-typed-movie.html.

This isn't perfect because, sometimes, type definitions fall out of sync with the corresponding library (for example, after a new release) or are flat-out wrong but, most of the time, they definitely improve the developer experience and code quality.

As a matter of fact, type definitions are also useful for JavaScript developers as they provide information about the library APIs that might not even be documented otherwise.

.NET and Java developers will feel at home

TypeScript will feel natural for any Java or .NET developer as it supports many of the concepts that developers with that background should be familiar with.

Career-wise, learning TypeScript is beneficial for any backend developer as more and more code is written using JavaScript and TypeScript nowadays.

TypeScript supports object-oriented programming (OOP) concepts through classes, inheritance, constructors, property accessors, methods, and interfaces. It also supports enums, generics, iterators, generators, modules, decorators (also known as annotations), and many others.

If you only consider the OOP and modularity features of TypeScript, you can easily understand that it makes it much simpler to structure and organize your code base while defining your domain model using familiar concepts.

Also, since it is a superset of JavaScript, it also has great support for functional programming.

Having prior experience with all these concepts certainly gives you an edge to quickly get up to speed with TypeScript.

If you're coming from Java, .NET, or a similar language, do not underestimate the differences between the language(s) you are familiar with and TypeScript; some are quite profound. For example, the this keyword exists both in JavaScript and TypeScript, but it behaves differently in both, which can be very surprising.

That being said, one of the reasons for me (Sébastien) to introduce TypeScript at work a few years back (2016), was to allow our Java development teams to participate in the development and maintenance of frontend applications. At the time, we were developing JavaServer Faces (JSF)-based web applications almost completely in Java, so the introduction of RESTful web services and single page applications was quite a revolution. The fact that we have chosen to use TypeScript really helped the teams to quickly get on board and, in hindsight, it was a really good choice.

Of course, the matter is more complex than this; it isn't because our developers could contribute to the elaboration of frontend application code that they became frontend developers overnight. In our humble opinion, frontend and backend developers usually have a fundamentally different focus during their work. Some have a good feeling for user experience and user interface development and some others just don't.

By now, you have enough background information about JavaScript, TypeScript, how they fit together, and why you have chosen the right language to learn at the right time.

So, let's get started, shall we?

What you'll need to install