100% found this document useful (6 votes)
32 views61 pages

Download Full TypeScript Basics: Learn TypeScript from Scratch and Solidify Your Skills with Projects 1st Edition Nabendu Biswas PDF All Chapters

TypeScript

Uploaded by

preabmisiti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
32 views61 pages

Download Full TypeScript Basics: Learn TypeScript from Scratch and Solidify Your Skills with Projects 1st Edition Nabendu Biswas PDF All Chapters

TypeScript

Uploaded by

preabmisiti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Download Full Version ebookmass - Visit ebookmass.

com

TypeScript Basics: Learn TypeScript from Scratch


and Solidify Your Skills with Projects 1st Edition
Nabendu Biswas

https://ebookmass.com/product/typescript-basics-learn-
typescript-from-scratch-and-solidify-your-skills-with-
projects-1st-edition-nabendu-biswas/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmass.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Practical GraphQL: Learning Full-Stack GraphQL Development


with Projects 1st Edition Nabendu Biswas

https://ebookmass.com/product/practical-graphql-learning-full-stack-
graphql-development-with-projects-1st-edition-nabendu-biswas/

ebookmass.com

Modern TypeScript: A Practical Guide to Accelerate Your


Development Velocity 1st Edition Ben Beattie-Hood

https://ebookmass.com/product/modern-typescript-a-practical-guide-to-
accelerate-your-development-velocity-1st-edition-ben-beattie-hood/

ebookmass.com

Modern TypeScript 1 / converted Edition Ben Beattie-Hood

https://ebookmass.com/product/modern-typescript-1-converted-edition-
ben-beattie-hood/

ebookmass.com

Bernard Bolzano: His Life and Work Paul Rusnock

https://ebookmass.com/product/bernard-bolzano-his-life-and-work-paul-
rusnock/

ebookmass.com
Korean from zero! All three books George Trombley

https://ebookmass.com/product/korean-from-zero-all-three-books-george-
trombley/

ebookmass.com

Health Reforms in Post-Communist Eastern Europe: The


Politics of Policy Learning Tamara Popic

https://ebookmass.com/product/health-reforms-in-post-communist-
eastern-europe-the-politics-of-policy-learning-tamara-popic/

ebookmass.com

eTextbook 978-0393265156 Psychology in Your Life 2nd


Edition by Sarah Grison

https://ebookmass.com/product/etextbook-978-0393265156-psychology-in-
your-life-2nd-edition-by-sarah-grison/

ebookmass.com

Understanding Large Language Models: Learning Their


Underlying Concepts and Technologies 1st Edition Thimira
Amaratunga
https://ebookmass.com/product/understanding-large-language-models-
learning-their-underlying-concepts-and-technologies-1st-edition-
thimira-amaratunga/
ebookmass.com

Conditions in Occupational Therapy: Effect on Occupational


Performance 5th Edition, (Ebook PDF)

https://ebookmass.com/product/conditions-in-occupational-therapy-
effect-on-occupational-performance-5th-edition-ebook-pdf/

ebookmass.com
Everyday Creativity and the Healthy Mind: Dynamic New
Paths for Self and Society 1st ed. Edition Ruth Richards

https://ebookmass.com/product/everyday-creativity-and-the-healthy-
mind-dynamic-new-paths-for-self-and-society-1st-ed-edition-ruth-
richards/
ebookmass.com
TypeScript Basics
Learn TypeScript from Scratch
and Solidify Your Skills
with Projects

Nabendu Biswas
TypeScript Basics: Learn TypeScript from Scratch and Solidify Your Skills
with Projects
Nabendu Biswas
Bhopal, India

ISBN-13 (pbk): 978-1-4842-9522-9 ISBN-13 (electronic): 978-1-4842-9523-6


https://doi.org/10.1007/978-1-4842-9523-6
Copyright © 2023 by Nabendu Biswas
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: James Robinson-Prior
Development Editor: James Markham
Coordinating Editor: Gryffin Winkler
Copy Editor: Kezia Endsley
Cover image designed by eStudioCalamar
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY
10004, U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected],
or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance
Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for
reprint, paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on GitHub (https://github.com/Apress). For more detailed information,
please visit https://www.apress.com/gp/services/source-code.
Paper in this product is recyclable
This book is affectionately dedicated to my wife and kid.
Table of Contents
About the Author���������������������������������������������������������������������������������ix

About the Technical Reviewer�������������������������������������������������������������xi

Introduction���������������������������������������������������������������������������������������xiii

Chapter 1: Getting Started��������������������������������������������������������������������1


Project Setup��������������������������������������������������������������������������������������������������������1
Summary��������������������������������������������������������������������������������������������������������������4

Chapter 2: TypeScript Basics����������������������������������������������������������������5


The Number Type��������������������������������������������������������������������������������������������������5
The String and Boolean Types�������������������������������������������������������������������������������7
Inference���������������������������������������������������������������������������������������������������������������7
Objects������������������������������������������������������������������������������������������������������������������8
Arrays������������������������������������������������������������������������������������������������������������������10
Complex Arrays����������������������������������������������������������������������������������������������11
Functions������������������������������������������������������������������������������������������������������������12
Union Types���������������������������������������������������������������������������������������������������������13
Literal Types��������������������������������������������������������������������������������������������������������14
Enum Types���������������������������������������������������������������������������������������������������������14
Optionals Type�����������������������������������������������������������������������������������������������������15
Interfaces and Types�������������������������������������������������������������������������������������������16
Running the Code������������������������������������������������������������������������������������������������18
Summary������������������������������������������������������������������������������������������������������������19

v
Table of Contents

Chapter 3: The TypeScript Compiler���������������������������������������������������21


Watch Mode��������������������������������������������������������������������������������������������������������21
Compiling an Entire Project���������������������������������������������������������������������������������22
rootDir and outDir�����������������������������������������������������������������������������������������������26
Summary������������������������������������������������������������������������������������������������������������27

Chapter 4: Classes and Interfaces������������������������������������������������������29


The Basics about Classes�����������������������������������������������������������������������������������29
Advanced Classes�����������������������������������������������������������������������������������������������34
Interface Basics��������������������������������������������������������������������������������������������������44
Summary������������������������������������������������������������������������������������������������������������49

Chapter 5: Advanced Types����������������������������������������������������������������51


Initial Setup���������������������������������������������������������������������������������������������������������51
Intersection Types�����������������������������������������������������������������������������������������������52
Type Guards and Discriminated Unions��������������������������������������������������������������53
Type Casting��������������������������������������������������������������������������������������������������������56
Index Properties��������������������������������������������������������������������������������������������������58
Function Overloading������������������������������������������������������������������������������������������59
Nullish Coalescing�����������������������������������������������������������������������������������������������61
Summary������������������������������������������������������������������������������������������������������������62

Chapter 6: Generics and Decorators���������������������������������������������������63


Initial Setup���������������������������������������������������������������������������������������������������������63
Array and Promise Types�������������������������������������������������������������������������������������64
Generic Functions�����������������������������������������������������������������������������������������������65
Type Constraints�������������������������������������������������������������������������������������������������66
Generic Classes��������������������������������������������������������������������������������������������������68
Generic Utilities���������������������������������������������������������������������������������������������������69

vi
Table of Contents

Decorators Setup������������������������������������������������������������������������������������������������69
Simple Decorators����������������������������������������������������������������������������������������������71
Decorator Factories���������������������������������������������������������������������������������������������73
Useful Decorators�����������������������������������������������������������������������������������������������74
Property Decorators��������������������������������������������������������������������������������������������75
Summary������������������������������������������������������������������������������������������������������������78

Chapter 7: Creating a To-­do List Project with TypeScript�������������������79


Initial Setup���������������������������������������������������������������������������������������������������������79
Creating the To-Do List����������������������������������������������������������������������������������������81
Summary������������������������������������������������������������������������������������������������������������86

Chapter 8: Creating a Drag-­and-­Drop Project with TypeScript�����������87


Initial Setup���������������������������������������������������������������������������������������������������������87
DOM Selection����������������������������������������������������������������������������������������������������89
Rendering a List��������������������������������������������������������������������������������������������������95
Filtering Logic���������������������������������������������������������������������������������������������������102
Abstract Class���������������������������������������������������������������������������������������������������107
Rendering Items������������������������������������������������������������������������������������������������112
Draggable Items������������������������������������������������������������������������������������������������115
Summary����������������������������������������������������������������������������������������������������������122

Chapter 9: Improving the Drag-and-Drop Project�����������������������������123


Changing to ES6 Modules���������������������������������������������������������������������������������123
Using Webpack�������������������������������������������������������������������������������������������������134
Summary����������������������������������������������������������������������������������������������������������140

vii
Table of Contents

Chapter 10: Creating a Party App in ReactJS with TypeScript���������141


Party App�����������������������������������������������������������������������������������������������������������141
Listing People���������������������������������������������������������������������������������������������������142
Adding People���������������������������������������������������������������������������������������������������146
Summary����������������������������������������������������������������������������������������������������������151

Chapter 11: Using React Redux with TypeScript������������������������������153


Setting Up the Project���������������������������������������������������������������������������������������153
Setting Up Redux����������������������������������������������������������������������������������������������154
The Output��������������������������������������������������������������������������������������������������������157
Summary����������������������������������������������������������������������������������������������������������160

Index�������������������������������������������������������������������������������������������������161

viii
About the Author
Nabendu Biswas is a full stack JavaScript
developer. He has worked in the IT industry
for the past 18 years for the world’s top
development firms and investment banks.
He is a passionate tech blogger and YouTuber
and he currently works as an Architect in an
IT company at Bhopal. He is the author of five
books, all published by Apress. His books cover
Gatsby, MERN, and React Firebase.

ix
About the Technical Reviewer
Alexander Nnakwue has a background
in mechanical engineering. He is a senior
software engineer with over seven years of
experience in various industries, including
payments, blockchain, and marketing
technologies. He is a published author in
professional JavaScript, as well as a technical
writer and reviewer. Currently, he is working as
a software engineer at Konecranes, helping the
digital experience team with machine data and industrial cranes.
In his spare time, he loves to listen to music and enjoys the game of
soccer. He currently lives in Helsinki, Finland with his lovely wife.

xi
Introduction
TypeScript is revolutionizing how developers create JavaScript apps. It
was built by Microsoft to fix the issues that came out of loose binding in
JavaScript. Since JavaScript is a loosely typed language, a lot of issues
ended up in the production apps. These issues were hard to track and took
a lot of time to fix.
TypeScript is a superset of JavaScript, and it enables you to avoid type
errors before they even occur. You can catch them in an IDE (Integrated
Development Environment) like VS Code. The popular JavaScript frontend
framework of Angular uses TypeScript by default. The most popular
JavaScript frontend library called React also uses JavaScript by default.
This book first teaches you about TypeScript, and then you will use
it in a ReactJS project. You will also use it with the JavaScript backend
framework of NodeJS and learn how to create a React Redux project.

xiii
CHAPTER 1

Getting Started
Welcome to TypeScript Basics, where you’ll learn TypeScript from scratch
and solidify your skills by creating some projects. TypeScript is a superset
of JavaScript and was built by Microsoft to fix the issues of loose binding in
JavaScript.
After learning the fundamentals of TypeScript in the first six chapters,
you will use that information to create the following projects:

• A to-do list (Chapter 7)

• A drag-and-drop project (Chapters 8 and 9)

• A party app (Chapter 10)

• A React Redux TypeScript project (Chapter 11)

With TypeScript, you get all the new features of JavaScript, through
which you can avoid type errors before they occur. The limitation of
TypeScript is that browsers can’t execute it.
Browsers only understand JavaScript, so TypeScript needs to be
compiled to JavaScript. This chapter starts with the basic setup.

Project Setup
Open a new folder in VS Code and create a basic index.html file in it (see
Listing 1-1). This example also refers to a JavaScript file called main.js.

© Nabendu Biswas 2023 1


N. Biswas, TypeScript Basics, https://doi.org/10.1007/978-1-4842-9523-6_1
Chapter 1 Getting Started

Listing 1-1. Basic index.html File

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,
initial-­scale=1.0">
    <title>TypeScript Basics</title>
</head>
<body>
    <h1>TypeScript Basics</h1>
    <script src="main.js"></script>
</body>
</html>

Next, install TypeScript globally on your system with the following


command. Add a sudo if you are using a Mac or Linux system.

1   npm i -g typescript

Now, create the main.ts file and add a simple console.log to it. The
browser only understands JavaScript, so you have to change it to JavaScript
using the tsc main.ts command. The tsc command runs the TypeScript
compiler and converts the TypeScript file to JavaScript. This command will
create a new main.js JavaScript file in the same directory. See Figure 1-1.

2
Chapter 1 Getting Started

Figure 1-1. Simple main.ts

You will also be using the awesome extension of Live Server in this
project (see Figure 1-2) so that you don’t have to rerun the project after
every change.

Figure 1-2. Live Server

3
Chapter 1 Getting Started

Summary
In this introductory chapter, you completed the basic setup for TypeScript.
You installed TypeScript globally and created basic HTML and TypeScript
files and made them work together.

4
CHAPTER 2

TypeScript Basics
This chapter starts your TypeScript journey. Here, you will learn about
different types and ways to use them in your projects. You will start with
the number type, followed by the string and Boolean types. You will also
learn about many more types and end by learning about interfaces.

The Number Type


Create an index.ts file in your earlier setup. Then add the code in
Listing 2-1 to it. You have two variables—myNum and anotherNum. The code
gives anotherNum the number type.
That means the myNum and anotherNum variables cannot take anything
other than numbers.

Listing 2-1. Number Types

//Numbers
let myNum = 10;
let anotherNum: number = 20;

myNum = 12;
myNum = '12';

anotherNum = 30;
anotherNum = false;

© Nabendu Biswas 2023 5


N. Biswas, TypeScript Basics, https://doi.org/10.1007/978-1-4842-9523-6_2
Chapter 2 TypeScript Basics

If you hover your mouse over the error, you can see the real issues, as
shown in Figures 2-1 and 2-2.

Figure 2-1. Number issue

Figure 2-2. Boolean issue

As you can see in this example, even if you don’t assign a type,
TypeScript infers a type. Hover the mouse over myNum and it will show the
number type. See Figure 2-3.

6
Chapter 2 TypeScript Basics

Figure 2-3. TypeScript

The String and Boolean Types


The same is true for the String and Boolean types. When you first assign a
type and then give the wrong type, you will get an error. Second, the types
are inferred. That means if you don’t provide a type, TypeScript will assign
one depending on the value. See Listing 2-2.

Listing 2-2. String and Boolean types

//String
let myStr: string = 'Hello';
let anotherStr = 'World';
myStr = true;
anotherStr = 45;
//Boolean
let myBool: boolean = true;
let anotherBool = false;

myBool = 'true';
anotherBool = 76;

Inference
So, you might wonder when to assign a type and when is it better to let
TypeScript automatically assign it?

7
Chapter 2 TypeScript Basics

In most cases, you should leave it to TypeScript to assign the type. In


Listing 2-3, the salary variable wasn’t assigned a type.
Later on, you will assign a number, string, and Boolean type to it.

Listing 2-3. Wrong Types

//Inference
let salary;
salary = 12000;
salary = '12000';
salary = true;

Now, this is not right. When you want to assign a value later, you’ll
provide an explicit type.
You will now start getting type errors, as shown in Listing 2-4.

Listing 2-4. Type Errors with Inference

//Inference
let salary:number;
salary = 12000;
salary = '12000';
salary = true;

Objects
This section explains what objects are in TypeScript. In the example in
Listing 2-5, an object that has two strings is given one number and one
Boolean type.
If you hover your mouse over the object, it will indicate the data types.

8
Chapter 2 TypeScript Basics

Listing 2-5. Object with No Types

//Objects
const developer = {
    firstName: 'Nabendu',
    lastName: 'Biswas',
    age: 40,
    isTrainer: true
}

Now create a new object where you will give the type of each key (see
Listing 2-6). You will get an error if you try to assign a different value to a
key or to a key that doesn’t exist. See Figure 2-4.

Listing 2-6. Object with Types

const newDeveloper: { name: string; age: number; isDev:


boolean } = {
    name: 'Mousam',
    age: 39,
    isDev: true
}

newDeveloper.name = 'Mousam Mishra';


newDeveloper.age = 'Forty';
newDeveloper.firstName = 'Mousam';

9
Chapter 2 TypeScript Basics

Figure 2-4. Object errors

Arrays
This section looks at arrays. In TypeScript, if you provide an array of
strings, such as languages in the following example, you cannot push a
number or Boolean type to that array.
You can also explicitly declare that you have an array of a certain type,
such as declaring an array of number types. See Listing 2-7.

10
Chapter 2 TypeScript Basics

Listing 2-7. Arrays with Types

//Arrays
const languages = ['React', 'Angular', 'Vue'];

languages.push('TypeScript');
languages.push(56);
languages.push(true);

const numbers: number[] = [51, 22, 33];


numbers.push(56);
numbers.push('56');
numbers.push(true);

Complex Arrays
In this section, you learn to create an array of objects. You provide the type
and you indicate the type of keys in the object (see Listing 2-8).

Listing 2-8. Complex Arrays with Types

const arrOfObj: { name: string; age: number }[] = [


    { name: 'Nabendu', age: 40 },
    { name: 'Mousam', age: 39 }
];
arrOfObj.push({ name: 'Shikha', age: 39 });
arrOfObj.push({ name: 'Hriday', age: 'Eight' });

If you want to write the array type, you need to use two brackets [] in
the type inference, as shown in Listing 2-9.

11
Chapter 2 TypeScript Basics

Listing 2-9. More Complex Arrays with Types

const arrOfArrays: number[][] = [


    [11, 32, 43],
    [34, 75, 64]
];

arrOfArrays.push([21, 32, 13]);

Functions
This section looks at the example of functions. Suppose you need to add
two numbers and create a function called addNums to do so.
If you don’t provide the type, you will not get an error even if you give
one string. See Listing 2-10.

Listing 2-10. Functions

//Functions
const addNums = (num1, num2) => {
    return num1 + num2;
}

addNums(10, 20);
addNums(10, '20');

You should always provide the type, as in multiNums. It is also


advisable to provide the return type, as it can catch the error if you provide
the wrong return type, as in modNums.
If you don’t give a return type, you should provide void, as shown in
printSum in Listing 2-11.

12
Chapter 2 TypeScript Basics

Listing 2-11. Function Types

const multiNums = (num1: number, num2: number) => {


    return num1 * num2;
}

multiNums(10, 20);
multiNums(10, '20');

const modNums = (num1: number, num2: number): number => {


    // return num1 % num2;
    return num1 > num2
}

modNums(10, 20);
modNums(10, '20');

const printSum = (num1: number, num2: number): void => {


    console.log(num1 + num2);
}

printSum(10, 20);
printSum(10, '20');

Union Types
You can also create union types, in which a variable can have multiple
types. Say you have a variable called numOrStr, which can be a number or
string type.
You can also have an array, which can only contain elements of the
number or string type. See Listing 2-12.

13
Chapter 2 TypeScript Basics

Listing 2-12. Union Types

//Union types
let numOrStr: number | string;
numOrStr = 10;
numOrStr = 'Ten';

let arr: (number | string )[] = [10, 'Ten', true];

Literal Types
With literal types, you specify only the acceptable terms. For example, in
the myLiteral type, Nabendu, Mousam, Shikha, and Hriday are the only
acceptable values.
Listing 2-13 uses Parag and the program returns errors.

Listing 2-13. Literal Types

//Literal types
let myLiteral: 'Nabendu' | 'Mousam' | 'Shikha' | 'Hriday' =
'Nabendu';

myLiteral = 'Mousam';
myLiteral = 'Shikha';
myLiteral = 'Hriday';
myLiteral = 'Parag';

Enum Types
This section looks at enum, which is a combination of the union type and
the literal type. Listing 2-14 provides a predefined type with the enum
variable.

14
Chapter 2 TypeScript Basics

After that, you can use it in your code.

Listing 2-14. Enum Types

//Enum
enum Role { ADMIN, READ_ONLY, AUTHOR };

const myRole = Role.ADMIN;


const hridayRole: Role = Role.AUTHOR;

Optionals Type
This section looks at optionals. Suppose you want an age field, which
should be a number.
In the example in Listing 2-15, in optionalObj, the age is declared as
a number and is undefined. The problem with this approach is that you
need to leave it undefined if you don’t want to specify it.
In the betterOptObj example, the age is indicated with ?, which means
if you provide it, it should be a number, but it is not required.

Listing 2-15. Optionals Types

//Optionals
let optionalObj: { name: string; age: number | undefined } = {
    name: 'Nabendu',
    age: undefined
};

let betterOptObj: { name: string; age?: number } = {


    name: 'Nabendu'
};

15
Chapter 2 TypeScript Basics

Interfaces and Types


This section looks at interfaces. They are a better way to provide types for
different properties of an object. Listing 2-16 shows a Developer interface
that includes some properties.
You can use this interface in two different variables, called person1 and
person2.

Listing 2-16. Interfaces

//Interfaces
interface Developer {
    name: string;
    age: number;
    isDev: boolean;
}

const person1: Developer = {


    name: 'Nabendu',
    age: 40,
    isDev: true
}

const person2: Developer = {


    name: 'Mousam',
    age: 39,
    isDev: true
}

Types are similar to interfaces. As you can see in Listing 2-17, they are
used in DeveloperType.
Interfaces can be used only in objects, whereas types can be used in
strings, arrays of objects, or anything else.

16
Chapter 2 TypeScript Basics

Listing 2-17. Types

//Types
type DeveloperType = {
    name: string;
    age: number;
    isDev: boolean;
}

const person3: DeveloperType = {


    name: 'Nabendu',
    age: 40,
    isDev: true
}

type PersonName = string;


const person4: PersonName = 'Nabendu';

type CoderType = {
    name: string;
    category: 'frontend' | 'backend' | 'mobile';
    age: number;
}[];

const coder1: CoderType = [


    {  name: 'Nabendu', category: 'frontend', age: 40 },
    {  name: 'Mousam', category: 'backend', age: 39 },
]

17
Chapter 2 TypeScript Basics

Running the Code


Since the index.ts file has a lot of errors, you will add a bit of it to the
main.ts file. You also need to run the tsc main.ts command to convert
the code into a JavaScript file. See Listing 2-18.

Listing 2-18. Running the Code

//Types
type DeveloperNewType = {
    name: string;
    age: number;
    isDev: boolean;
}
const person5: DeveloperNewType = {
    name: 'Nabendu',
    age: 40,
    isDev: true
}
console.log('${person5.name} is a ${person5.isDev} Dev and is
${person5.age} years old');

Now, in the localhost, you can see the desired console log (see
Figure 2-5).

18
Chapter 2 TypeScript Basics

Figure 2-5. The console

Summary
In this chapter, you learned about different types in TypeScript. You
learned about the number type and then moved to string and Boolean
types. After learning about object and array types, you learned about
complex arrays. Then you learned about union, literal, enum, and optional
types. The chapter ended by discussing interfaces.

19
CHAPTER 3

The TypeScript
Compiler
When you run the TypeScript file every time, you are making changes to it.
In this chapter, you learn about other ways to watch for and make changes.

Watch Mode
You can watch the changes in the main.js file by using watch mode. Then
you don’t have to run the file after each change. You need to run the tsc
command with the -w flag, as follows:

1   tsc main.ts -w

If you then add anything to the file, it will be converted into the
corresponding JavaScript file. See Listing 3-1.

Listing 3-1. New Code

type PersonNewName = string;


const person6: PersonNewName = 'Mousam';
console.log(`New Developer is ${person6}`);

You can see the new changes in the localhost (see Figure 3-1).

© Nabendu Biswas 2023 21


N. Biswas, TypeScript Basics, https://doi.org/10.1007/978-1-4842-9523-6_3
Chapter 3 The TypeScript Compiler

Figure 3-1. Local changes

Compiling an Entire Project


To compile an entire project, you have to make it a TypeScript project. You
need to run the tsc –init command, which will create a tsconfig.json
file in the root directory. See Figure 3-2.

22
Chapter 3 The TypeScript Compiler

Figure 3-2. Compiling a project

You can then run the tsc command to compile all the TypeScript files.
However, the index.ts file has a lot of errors. Figure 3-3 shows one of
these errors.

23
Chapter 3 The TypeScript Compiler

Figure 3-3. The tsc error

You need to exclude this file by adding an exclude to the tsconfig.


json file. Now, when you run the tsc command, you will not get an error
(see Figure 3-4).

24
Chapter 3 The TypeScript Compiler

Figure 3-4. The tsc file again, without the error

You can also exclude all the node_modules, which are created when
you use a third-party library. Sometimes they contain TypeScript code and
you don’t want to compile them.
Similar to using exclude, you have use include to add the mentioned
files. In the example in Figure 3-5, the main.ts file is included.

25
Chapter 3 The TypeScript Compiler

Figure 3-5. This include adds the main.ts file

rootDir and outDir


To organize your TypeScript project, you should keep all the TypeScript
files in a src folder.
You have put the index.ts and main.ts files in the src folder. Also
create a dist folder.
In the tsconfig.json file, uncomment rootDir and outDir. This is
where you put the respective folders (see Figure 3-6). You also have to run
the tsc command; it is not throwing an error.

26
Chapter 3 The TypeScript Compiler

Figure 3-6. The tsconfig.json file

You can now see the main.js file in the dist folder (see Figure 3-7).
You also need to change the path of the main.js file in the index.html file.

Figure 3-7. The index.html file

Summary
In this chapter, you learned to configure your TypeScript projects properly.
27
CHAPTER 4

Classes and
Interfaces
This chapter covers classes and interfaces. In order to follow along, you
should have basic knowledge of ES6 classes.

The Basics about Classes


TypeScript classes have some special features. TypeScript classes can have
public and private variables, like OOP languages such as Java and C++ do.
Listing 4-1 shows a class called CreateRoom. It has a public variable
called room and a private family array.
You can add values to the family array only by using the
addFamilyMember function and you can get values using the showFamily
function.

Listing 4-1. Classes

//Classes
class CreateRoom{
    public room: string;
    private family: string[] = [];
    constructor(name: string){
        this.room = '${name}s room'
    }

© Nabendu Biswas 2023 29


N. Biswas, TypeScript Basics, https://doi.org/10.1007/978-1-4842-9523-6_4
Chapter 4 Classes and Interfaces

    addFamilyMember(member: string){
        this.family.push(member);
    }
    showFamily(){
        console.log(this.family);
    }
    cleanRoom(soap: string){
        console.log('Cleaning ${this.room} with ${soap}');
    }
}

const nabendu = new CreateRoom('Nabendu');


const shikha = new CreateRoom('Shikha');
const hriday = new CreateRoom('Hriday');
const mousam = new CreateRoom('Mousam');
nabendu.family;
nabendu.addFamilyMember('Nabendu');
shikha.addFamilyMember('Shikha');
hriday.addFamilyMember('Hriday');
mousam.cleanRoom('Lizol');

You can also use read-only variables in TypeScript. In Listing 4-2,


dobShikha is a read-only variable. You can access it from outside of the
class, but you cannot update it.
You can make a variable private and read-only both (like dobHriday).
That way, you cannot access the variable from the outside.

Listing 4-2. Private and Read-Only Variables

//Classes
class CreateRoom{
    public room: string;
    private family: string[] = [];
    readonly dobShikha: string = '1982-12-12';

30
Chapter 4 Classes and Interfaces

    private readonly dobHriday: string = '2013-12-12';


    constructor(name: string){
        this.room = '${name}s room'
    }
    ...
}

const nabendu = new CreateRoom('Nabendu');


const shikha = new CreateRoom('Shikha');
const hriday = new CreateRoom('Hriday');
const mousam = new CreateRoom('Mousam');
shikha.dobShikha;
shikha.dobShikha = '1982-11-12';
hriday.dobHriday;
...
...

You can clean up a TypeScript class by using the constructor.


In Listing 4-3, room in the constructor has been removed and is now public.

Listing 4-3. Updating the Constructor

class CreateRoom{
    private family: string[] = [];
    readonly dobShikha: string = '1982-12-12';
    private readonly dobHriday: string = '2013-12-12';
    constructor(public room: string){
    }
    ...
    ...
    cleanRoom(soap: string){
        console.log('Cleaning ${this.room} with ${soap}');
    }
}

31
Random documents with unrelated
content Scribd suggests to you:
at Celorico, 124, 126, 134;
Francozo, 136;
his disposition of the troops, 174;
blockades Ciudad Rodrigo, 179, 196, 218;
invests Almeida, 179;
his victory of Fuentes d’Onoro, 179;
at St Vincente, 186;
title of Count of Vimiero, 201;
attack on Badajos, 218, 231, 234;
enters Castile, 220;
at Alfaiates, 252;
his plan of enlisting the Spaniards, 256;
his secret plans, 259, 272, 275;
moves on Rueda, 274;
at Villa Verde, 274;
formation of the army at the battle of Salamanca, 286;
pursuit of the enemy, 289, 292
Westmorland, 180, 184
Weyland, General, taken prisoner at Badajos, 243
White, Captain, his attack on the French at Ladoeiro, 164
White, Mr, wounded at the battle of Salamanca, 292
Whitelock, General, in command of an expedition in America, 1
Whittingham, appointed Colonel in the Spanish service, 23;
Brigadier, 75;
wounded, 75
Wilson, Major, wounded at the battle of Vimiero, 39
Wilson, Sir R., his defence of the Pass of Baños, 75;
his characteristics, 122;
his advance on Coimbra, 173

Yeltes river, 258


York, Duke of, 187

Zafra, 232
Zamora, 61, 76, 77;
evacuated, 297
Zamora bridge, 271
Zapardiel river, 274
Zeller, Frank van, 108
Zezere, 176

PRINTED BY OLIVER AND BOYD, EDINBURGH


*** END OF THE PROJECT GUTENBERG EBOOK LETTERS FROM THE
PENINSULA, 1808-1812 ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you


derive from the use of Project Gutenberg™ works
calculated using the method you already use to calculate
your applicable taxes. The fee is owed to the owner of the
Project Gutenberg™ trademark, but he has agreed to
donate royalties under this paragraph to the Project
Gutenberg Literary Archive Foundation. Royalty payments
must be paid within 60 days following each date on which
you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly
marked as such and sent to the Project Gutenberg Literary
Archive Foundation at the address specified in Section 4,
“Information about donations to the Project Gutenberg
Literary Archive Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of
receipt that s/he does not agree to the terms of the full
Project Gutenberg™ License. You must require such a user
to return or destroy all copies of the works possessed in a
physical medium and discontinue all use of and all access to
other copies of Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full


refund of any money paid for a work or a replacement
copy, if a defect in the electronic work is discovered and
reported to you within 90 days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
back
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like