0% found this document useful (0 votes)
5 views49 pages

TypeScript Tutorial

TypeScript is a superset of JavaScript that adds optional types to enhance code quality and prevent errors associated with dynamic typing. The tutorial covers setting up a TypeScript development environment, including installing Node.js, the TypeScript compiler, and Visual Studio Code, as well as writing a simple 'Hello, World!' program. It also explains the importance of TypeScript's type system in avoiding common issues found in JavaScript, such as property referencing errors and argument type mismatches.

Uploaded by

awaretejas55
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
0% found this document useful (0 votes)
5 views49 pages

TypeScript Tutorial

TypeScript is a superset of JavaScript that adds optional types to enhance code quality and prevent errors associated with dynamic typing. The tutorial covers setting up a TypeScript development environment, including installing Node.js, the TypeScript compiler, and Visual Studio Code, as well as writing a simple 'Hello, World!' program. It also explains the importance of TypeScript's type system in avoiding common issues found in JavaScript, such as property referencing errors and argument type mismatches.

Uploaded by

awaretejas55
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

TypeScript Tutorial – QA Mitra

Introduction to TypeScript
TypeScript is a superset of JavaScript.

TypeScript builds on top of JavaScript. First, you write the TypeScript code. Then,
you compile the TypeScript code into plain JavaScript code using a TypeScript
compiler.

Once you have the plain JavaScript code, you can deploy it to any environment that
JavaScript runs.

TypeScript files use the .ts extension rather than the .js extension of JavaScript files.

TypeScript uses the JavaScript syntaxes and adds additional syntaxes for supporting
Types.
If you have a JavaScript program without any syntax errors, it is a TypeScript
program. This means that all JavaScript programs are TypeScript programs. This is
very helpful if you migrate an existing JavaScript codebase to TypeScript.

The following diagram shows the relationship between TypeScript and JavaScript:

QA Mitra – One Stop Shop for QA


Why TypeScript

The main goals of TypeScript are:

 Introduce optional types to JavaScript.

JavaScript:

function add(x, y) {

return x + y;
}

TypeScript:

function add(x: number, y: number) : number {

return x + y;

QA Mitra – One Stop Shop for QA


TypeScript Setup

Summary: in this section, you’ll learn how to set up a TypeScript development


environment.

The following tools you need to set up to start with TypeScript:


 [Link] – [Link] is the environment in which you will run the TypeScript
compiler. Note that you don’t need to know [Link].
 TypeScript compiler – a [Link] module that compiles TypeScript into
JavaScript.
 Visual Studio Code or VS Code – a code editor supporting TypeScript. VS
Code is highly recommended. However, you can use your favourite editor.

If you use VS Code, you can install the following extension to speed up the
development process:

 Live Server – allows you to launch a development local web server with the
hot reload feature.

Install [Link]

To install [Link], you follow these steps:

 Go to the [Link] download page.

 Download the suitable [Link] version for your platform such as Windows,
macOS, or Linux.

 Execute the downloaded [Link] package or execution file. The installation is


quite straightforward.

 Verify the installation by opening the Terminal on macOS and Linux or the
Command Prompt on Windows and typing the command node -v, you should
see the installed version of [Link].

Install TypeScript compiler

To install the TypeScript compiler, you launch the Terminal on macOS or Linux and
Command Prompt on Windows and type the following command:

npm install -g typescript

After the installation, you can type the following command to check the current
version of the TypeScript compiler:

tsc --v
It should return the version like this:

QA Mitra – One Stop Shop for QA


Version 22.0.1

Note that your version is probably newer than this version.


If you’re on Windows and get the following error:

'tsc' is not recognized as an internal or external command, operable program or


batch file.

… then you should add the following


path C:\Users\<user>\AppData\Roaming\npm to the PATH variable. Notice that you
should change the <user> to your Windows user.

Install tsx module

If you want to run TypeScript code directly on [Link] without precompiling, you can
use the tsx module.

To install the tsx module globally, run the following command from the Terminal on
macOS and Linux or Command Prompt on Windows:

npm install -g tsx

Install VS Code

To install the VS Code, you follow these steps:

 Navigate to the VS Code download page.

 Download the latest version of VS Code that suits your OS (Windows,


macOS, or Linux)

 Execute the downloaded package or the installer file to launch the setup
wizard. The installation process is also quite straightforward.

 Launch the VS Code.

You’ll see the VS Code as shown in the following picture:

QA Mitra – One Stop Shop for QA


To install the Live Server extension, you follow these steps:

 Click the Extensions tab to find the extensions for VS Code.

 Type the live server to search for it.

 Click the install button to install the extension.

Summary

 A TypeScript compiler compiles the TypeScript into JavaScript.

 Use the tsc command to compile a TypeScript file to a JavaScript file.

QA Mitra – One Stop Shop for QA


 Use the tsx module to run TypeScript directly on [Link] without precompiling
it to JavaScript.

TypeScript “Hello, World!”

Summary: in this section, you’ll learn how to develop the Hello World program in
TypeScript.

TypeScript Hello World program in [Link]

1. Create a new directory to store the code, e.g., helloworld.


2. Launch VS Code and open the newly created directory.
3. Create a new TypeScript file called [Link]. The extension of a TypeScript file
is .ts.
4. Type the following source code in the [Link] file:
let message: string = 'Hello, World!';

[Link](message);

5. Launch a new Terminal within the VS Code by using the keyboard


shortcut Ctrl+` or follow the menu Terminal > New Terminal

6. Type the following command on the Terminal to compile the [Link] file:

QA Mitra – One Stop Shop for QA


tsc [Link]

If everything is fine, you’ll see a new file called [Link] is generated by the TypeScript
compiler:

To run the [Link] file in [Link], you use the following command:

node [Link]
If you installed the tsx module mentioned in the 2 . TypeScript Setup, you can use
just one command to run the TypeScript file directly on [Link] without precompiling
it to JavaScript:

tsx [Link]

Why TypeScript
Summary: in this section, you’ll learn why you should use TypeScript over
JavaScript to avoid the problems created by the dynamic types.

QA Mitra – One Stop Shop for QA


Why use TypeScript

There are two main reasons to use TypeScript:

 TypeScript adds a type system to help you avoid many problems with
dynamic types in JavaScript.

 TypeScript implements the future features of JavaScript.

This section focuses on the first reason.

Understanding dynamic type in JavaScript

JavaScript is dynamically typed. Unlike statically typed languages such as Java or


C#, values have types instead of variables. For example:

"Hello"

From the value, you can tell that its type is string.

The following value is a number:


2024

See the following example:

let box;

box = "hello";

box = 100

The type of the box variable changes based on the value assigned to it.
To find the type of the box variable at runtime, you use the typeof operator:

let box;

[Link](typeof(box)); // undefined

box = "Hello";

[Link](typeof(box)); // string

box = 100;
[Link](typeof(box)); // number

In this example, the first statement defines a variable box without assigning a value.
Its type is undefined.

QA Mitra – One Stop Shop for QA


Then, we assign the literal string "Hello" to box variable and show its type. The type
of the box variable changes to string.

Finally, we assign 100 to the box variable. This time, the type of the box variable
changes to number.

As you can see, as soon as the value is assigned, the type of the variable changes.

And you don’t need to explicitly tell JavaScript the type. JavaScript will automatically
infer the type from the value.

Dynamic types offer flexibility. However, they also lead to problems.


Problems with dynamic types

Suppose you have a function that returns a product object based on an id:

function getProduct(id){

return {

id: id,

name: `Awesome Gadget ${id}`,

price: 99.5

The following uses the getProduct() function to retrieve the product with id 1 and
show its data:

const product = getProduct(1);

[Link](`The product ${[Link]} costs $${[Link]}`);

Output:

The product undefined costs $99.5

It isn’t what we expected.

The issue with this code is that the product object doesn’t have the Name property. It
has the name property with the first letter n in lowercase.

However, you can only know it until you run the script.
Referencing a property that doesn’t exist on the object is a common issue when
working in JavaScript.

The following example defines a new function that outputs the product information to
the console:

QA Mitra – One Stop Shop for QA


const showProduct = (name, price) => {

[Link](`The product ${name} costs $${price}.`);

};

The following uses the getProduct() and showProduct() functions:

const product = getProduct(1);

showProduct([Link], [Link]);

Output:

The product 99.5 costs $Awesome Gadget 1


This time we pass the arguments in the wrong order to the showProduct() function.
This is another common problem that you often have when working with JavaScript.
This is why TypeScript comes into play.

How Typescript solves problems of dynamic types

To fix the problem of referencing a property that doesn’t exist on an object, you do
the following steps:

First, define the “shape” of the product object using an interface.

interface Product{

id: number,

name: string,

price: number
};

Second, explicitly use the Product type as the return type of


the getProduct() function:

function getProduct(id) : Product{


return {

id: id,

name: `Awesome Gadget ${id}`,

price: 99.5

QA Mitra – One Stop Shop for QA


When you reference a property that doesn’t exist, the code editor will inform you
immediately:

const product = getProduct(1);


[Link](`The product ${[Link]} costs $${[Link]}`);

The code editor highlighted the following error on the Name property:

And when you hover the mouse cursor over the error, you’ll see a hint that helps you
to solve the issue:

To solve the problem of passing the arguments in the wrong order, you explicitly
assign types to function parameters:

const showProduct = (name: string, price:number) => {

[Link](`The product ${name} costs $${price}.`);

};

And when you pass the arguments of the wrong types to the showProduct() function,
you’ll receive an error:

const product = getProduct(1);

showProduct([Link], [Link]);Code language: JavaScript (javascript)

QA Mitra – One Stop Shop for QA


TypeScript Data Types
Summary: in this section, you’ll learn about the TypeScript datatypes and their
purposes.

What is a type in TypeScript

In TypeScript, a type is a convenient way to refer to different properties and functions


that a value has.

A value is anything you can assign to a variable e.g., a number, a string, an array, an
object, and a function.

For example, see the following value:

'Hello'

When you look at this value, you can say it is a string. This value has properties and
methods that a string has.

For example, the 'Hello' value has a property called length that returns the number of
characters:

[Link]('Hello'.length);

It also has many methods like match(), indexOf(), and toUpperCase(). For example:

[Link]('Hello'.toUpperCase()); // HELLO

When you look at the value 'Hello' and describe it by listing the properties and
methods, it would be inconvenient.
A shorter way to refer to a value is to assign it a type. In this example, you
say 'Hello' is a string. Then, you know that you can use the properties and methods
of a string for the value 'Hello'.

In conclusion, in TypeScript:
 a type is a label that describes the different properties and methods that a
value has

 every value has a type.

DataTypes in TypeScript

TypeScript inherits the built-in types from JavaScript. TypeScript types are
categorized into:

 Primitive types.

 Object types.
Primitive types

QA Mitra – One Stop Shop for QA


The following illustrates the primitive types in TypeScript:

Name Description

string Represent text data.

number Represent numeric values.

boolean Have true and false values.

Null Have one value: null.

Undefined Have one value: undefined. It is the default value of an uninitialized variable.

Any Can allow any value

Object types

Object types are functions, arrays, classes, etc.


Purposes of types in TypeScript

There are two main purposes of types in TypeScript:

 First, types are used by the TypeScript compiler to analyze your code for
errors.

 Second, types allow you to understand what values are associated with
variables.

TypeScript Type Inference


Summary: in this section, you will learn about type inference in TypeScript.

Type inference describes where and how TypeScript infers types when you don’t
explicitly annotate them.

Basic type inference


When you declare a variable, you can use a type annotations to explicitly specify a
type for it. For example:

let counter: number;

QA Mitra – One Stop Shop for QA


However, if you initialize the counter variable with a number, TypeScript will infer the
type of the counter to be number. For example:

let counter = 0;
It is equivalent to the following statement:

let counter: number = 0;

Likewise, when you assign a function parameter a value, TypeScript infers the type
of the parameter to the type of the default value. For example:

function setCounter(max=100) {

// ...

In this example, TypeScript infers the type of the max parameter to be number.

Similarly, TypeScript infers the following return type of the increment() function
as number:

function increment(counter: number) {

return counter++;

It is the same as:

function increment(counter: number) : number {

return counter++;

The best common type algorithm

Consider the following assignment:

let items = [1, 2, 3, null];


To infer the type of items variable, TypeScript needs to consider the type of each
element in the array.

It uses the best common type algorithm to analyze each candidate type and select
the type that is compatible with all other candidates.
In this case, TypeScript selects the number or null array type (number | null) []) as
the best common type. Note that the | means the OR operator in types.

If you add a string to the items array, TypeScript will infer the type for the items as an
array of numbers and strings: (number | string)[]

QA Mitra – One Stop Shop for QA


let items = [1, 2, 3, 'Cheese'];

Type inference vs. Type annotations

The following shows the difference between type inference and type annotations:

Type inference Type annotations

TypeScript guesses the type You explicitly tell TypeScript the type

So, when do you use type inference and type annotations?


In practice, you should always use the type inference as much as possible. You use
the type annotation in the following cases:

 When you declare a variable and assign it a value later.

 When you want a variable that can’t be inferred.

 When a function returns the any type, you need to clarify the value.

Summary

 Type inference occurs when you initialize variables, set parameter default
values, and determine function return types.

 TypeScript uses the best common type algorithm to select the best candidate
types that are compatible with all variables.

 TypeScript also uses contextual typing to infer types of variables based on the
locations of the variables.

TypeScript Number Datatype


Summary: in this section, you’ll learn about the TypeScript number data types.

All numbers in TypeScript are either floating-point values or big integers. The
floating-point numbers have the type number while the big integers get the
type bigint.

The number type

The following shows how to declare a variable that holds a floating-point value:
let price: number;

Alternatively, you can initialize the price variable to a number:


let price = 9.95;

QA Mitra – One Stop Shop for QA


Decimal numbers

The following shows some decimal numbers:

let counter: number = 0;

let x: number = 100,

y: number = 200;

Big Integers

The big integers represent the whole numbers larger than 2 53 – 1. A Big integer
literal has the n character at the end of an integer literal like this:

let big: bigint = 9007199254740991n;

Summary

 All numbers in TypeScript are either floating-point values that get the number
type or big integers that get the bigint type.

TypeScript String Datatype

Summary: in this section, you’ll learn about the TypeScript string data type.

Like JavaScript, TypeScript uses double quotes (") or single quotes (') to surround
string literals:

let firstName: string = 'John';

let title: string = "Web Developer";

TypeScript also supports template strings that use the backtick (`) to surround
characters.

The template strings allow you to create multi-line strings and provide string
interpolation features.

The following example shows how to create a multi-line string using the backtick (`):

let description = `This TypeScript string can

span multiple

lines

`;
String interpolations allow you to embed the variables into the string like this:

QA Mitra – One Stop Shop for QA


let firstName: string = `John`;

let title: string = `Web Developer`;

let profile: string = `I'm ${firstName}.

I'm a ${title}`;

[Link](profile);

Output:

I'm John.
I'm a Web Developer.

Summary

 In TypeScript, all strings get the string type.

 Like JavaScript, TypeScript uses double quotes ("), single quotes ('), and
backtick (`) to surround string literals.

TypeScript Boolean Datatype


Summary: in this section, you will learn about the TypeScript boolean data type and
how to use the boolean keyword.

Introduction to the TypeScript boolean


The TypeScript boolean type has two values: true and false. The boolean type is one
of the primitive types in TypeScript.

Declaring boolean variables

In TypeScript, you can declare a boolean variable using the boolean keyword. For
example:

let pending: boolean;

pending = true;

// after a while

// ..

pending = false;
Boolean operator

QA Mitra – One Stop Shop for QA


To manipulate boolean values, you use the boolean operators. TypeScript supports
common boolean operators:

Operator Meaning

&& Logical AND operator

|| Logical OR operator

! Logical NOT operator

For example:

// NOT operator

const pending: boolean = true;

const notPending = !pending; // false

[Link](result); // false

const hasError: boolean = false;

const completed: boolean = true;

// AND operator

let result = completed && hasError;

[Link](result); // false

// OR operator

result = completed || hasError;

[Link](result); // true

Summary

 TypeScript boolean type has two values true and false.

 Use the boolean keyword to declare boolean variables.

TypeScript object Type

QA Mitra – One Stop Shop for QA


Summary: in this section, you’ll learn about the TypeScript object type and how to
write more accurate object type declarations.

Introduction to TypeScript object type


The TypeScript object type represents all values that are not in primitive types.

The following shows how to declare a variable that holds an object:

let employee: object;

employee = {

firstName: 'John',

lastName: 'Doe',

age: 25,

jobTitle: 'Web Developer'

};

[Link](employee);

Output:

firstName: 'John',
lastName: 'Doe',

age: 25,

jobTitle: 'Web Developer'

If you reassign a primitive value to the employee object, you’ll get an error :

employee = "Jane";

Error:

error TS2322: Type '"Jane"' is not assignable to type 'object'.

The employee object is an object type with a fixed list of properties. If you attempt to
access a property that doesn’t exist on the employee object, you’ll get an error:

[Link]([Link]);
Error:

QA Mitra – One Stop Shop for QA


error TS2339: Property 'hireDate' does not exist on type 'object'.

Note that the above statement works perfectly fine in JavaScript and
returns undefined instead.

To explicitly specify properties of the employee object, you first use the following
syntax to declare the employee object:

let employee: {

firstName: string;

lastName: string;

age: number;

jobTitle: string;

};

And then assign the employee object to a literal object with the described
properties:

employee = {

firstName: 'John',

lastName: 'Doe',

age: 25,

jobTitle: 'Web Developer'

};

Or you can combine both syntaxes in the same statement like this:

let employee: {

firstName: string;
lastName: string;

age: number;

jobTitle: string;

}={

firstName: 'John',

lastName: 'Doe',
age: 25,

QA Mitra – One Stop Shop for QA


jobTitle: 'Web Developer'

};

The empty type {}

TypeScript has another type called empty type denoted by {} , which is quite similar
to the object type.

The empty type {} describes an object that has no property on its own. If you try to
access a property on such an object, TypeScript will issue a compile-time error:

let vacant: {};

[Link] = 'John';

Error:

error TS2339: Property 'firstName' does not exist on type '{}'.

Summary
 The TypeScript object type represents any value that is not a primitive value.

 The Object type, however, describes functionality that is available on all


objects.

 The empty type {} refers to an object that has no property on its own.

TypeScript Array Type

Summary: in this section, you’ll learn about the TypeScript array type and its basic
operations.

Introduction to TypeScript array type


A TypeScript array is an ordered list of data. To declare an array that holds values of
a specific type, you use the following syntax:

let arrayName: type[];


For example, the following declares an array of strings:

let skills: string[] = [];

And you can add one or more strings to the array:


skills[0] = "Problem Solving";

QA Mitra – One Stop Shop for QA


skills[1] = "Programming";

or use the push() method:

[Link]('Software Design');

The following declares a variable and assigns an array of strings to it:

let skills = ['Problem Sovling','Software Design','Programming'];

In this example, TypeScript infers the skills array as an array of strings. It is


equivalent to the following:

let skills: string[];

skills = ['Problem Sovling','Software Design','Programming'];

After you define an array of a specific type, TypeScript will prevent you from adding
incompatible values. For example, the following will cause an error:

[Link](100);

… because we’re trying to add a number to the string array.


Error:

Argument of type 'number' is not assignable to parameter of type 'string'.

When you extract an element from the array, TypeScript infers the type of array
element. For example:

let skill = skills[0];

[Link](typeof(skill));

Output:

string

In this example, we extract the first element of the skills array and assign it to
the skill variable.

Since an element in a string array is a string, TypeScript infers the type of


the skill variable to string as shown in the output.

TypeScript array properties and methods

TypeScript arrays have the same properties and methods as JavaScript. For
example, the following uses the length property to get the number of elements in an
array:

let series = [1, 2, 3];


[Link]([Link]);

QA Mitra – One Stop Shop for QA


You can use all the useful array methods such as foreach(), map(), reduce(), filter()
For example:

let series = [1, 2, 3];


let doubleIt = [Link](e => e* 2);

[Link](doubleIt);

Output:

[ 2, 4, 6 ]

Storing values of mixed types

The following illustrates how to define an array that holds both strings and numbers:

let scores = ['Programming', 5, 'Software Design', 4];

In this case, TypeScript infers the scores array as an array of string | number. It’s
equivalent to the following:
let scores : (string | number)[];

scores = ['Programming', 5, 'Software Design', 4

Summary

 In TypeScript, an array is an ordered list of values.

 Use the let arr: type[] syntax to declare an array of a specific type. Adding a
value of a different type to the array will result in an error.

 An array can store values of mixed types. Use the arr: (type1 | type2) [] syntax
to declare an array of values with mixed types (type1, and type2)

TypeScript Tuple
Summary: in this section, you’ll learn about the TypeScript Tuple type and its usage.

Introduction to TypeScript Tuple type


A tuple works like an array with some additional considerations:

 The number of elements in the tuple is fixed.

 The types of elements are known, and need not be the same.

QA Mitra – One Stop Shop for QA


For example, you can use a tuple to represent a value as a pair of a string and
a number:

let skill: [string, number];


skill = ['Programming', 5];

The order of values in a tuple is important. If you change the order of values of
the skill tuple to [5, "Programming"], you’ll get an error:

let skill: [string, number];

skill = [5, 'Programming'];

Error:

error TS2322: Type 'string' is not assignable to type 'number'.

For this reason, it’s a good practice to use tuples with data that are related to each
other in a specific order.

For example, you can use a tuple to define an RGB color that always comes in a
three-number pattern:

(r,g,b)

For example:

let color: [number, number, number] = [255, 0, 0];


The color[0], color[1], and color[2] would be logically mapped
to Red, Green and Blue color values.
Optional Tuple Elements

Since TypeScript 3.0, a tuple can have optional elements specified using the
question mark (?) postfix.
For example, you can define an RGBA tuple with the optional alpha channel value:

let bgColor, headerColor: [number, number, number, number?];

bgColor = [0, 255, 255, 0.5];

headerColor = [0, 255, 255];

Note that the RGBA defines colors using the red, green, blue, and alpha models. The
alpha specifies the opacity of the color.

Summary
 A tuple is an array with a fixed number of elements whose types are known.

QA Mitra – One Stop Shop for QA


TypeScript any Type

Summary: in this section, you will learn about the TypeScript any type and how to
use it properly in your code.

Introduction to TypeScript any type

Sometimes, you may need to store a value in a variable. But you don’t know its type
when writing the program. And the unknown value may come from a third-party API
or user input.
In this case, you want to opt out of the type checking and allow the value to pass
through the compile-time check.

For example:

let result: any;

result = 1;

[Link](result);

result = 'Hello';

[Link](result);

result = [1, 2, 3];

const total = [Link]((a: number, b: number) => a + b, 0);


[Link](total);

Output: 6

In this example:

 First, declare the variable result with the type any.

 Second, assign number 1 to the result and display its value to the console.

 Third, assign the string literal 'Hello' to the result and show its value to the
console.

QA Mitra – One Stop Shop for QA


 Finally, assign an array of numbers to the result variable, calculate
the total using the reduce() method, and log the total to the console.

Let’s take another typical example:


// json may come from a third-party API

const json = `{"latitude": 10.11, "longitude":12.12}`;

// parse JSON to find location

const currentLocation = [Link](json);

[Link](currentLocation);

Code language: JavaScript (javascript)

Output:
{ latitude: 10.11, longitude: 12.12 }

In this example, TypeScript infers the value of the currentLocation variable as any.
We assign an object returned by the [Link]() function
the currentLocation variable.

However, when we access the non-existing property (x) of


the currentLocation variable, TypeScript does not carry any checks.

This is working fine and shows an undefined value in the console:


[Link](currentLocation.x);

Output:

undefined

The TypeScript compiler doesn’t complain or issue any errors.

The any type provides you with a way to work with the existing JavaScript codebase.
It allows you to gradually opt in and opt out of type-checking during compilation.
Therefore, you can use the any type for migrating a JavaScript project over to
TypeScript.

TypeScript any: implicit typing

If you declare a variable without specifying a type, TypeScript assumes that you use
the any type. This feature is called type Inference. TypeScript guesses the type of
the variable. For example:

let result;

QA Mitra – One Stop Shop for QA


In this example, TypeScript infers the type for you. This practice is called implicit
typing.

Summary
 The TypeScript any type allows you to store a value of any type. It instructs
the compiler to skip type-checking.

 Use the any type to store a value that you don’t know its type at the compile-
time or when you migrate a JavaScript project over to a TypeScript project.

TypeScript union Type


Summary: in this section, you will learn about the TypeScript union type that allows
you to store a value of one or several types in a variable.
Introduction to TypeScript union type

Sometimes, you will run into a function that expects a parameter that is either a
number or a string. For example:

function add(a: any, b: any) {

if (typeof a === 'number' && typeof b === 'number') {

return a + b;

if (typeof a === 'string' && typeof b === 'string') {


return [Link](b);

throw new Error('Parameters must be numbers or strings');


}

In this example, the add() function will calculate the sum of its parameters if they are
numbers.

If the parameters are strings, the add() function will concatenate them into a single
string.

If the parameters are neither numbers nor strings, the add() function throws an error.

The problem with the parameters of the add() function is that its parameters have
the any type. It means that you can call the function with arguments that are neither
numbers nor strings, the TypeScript will be fine with it.

QA Mitra – One Stop Shop for QA


This code will be compiled successfully but cause an error at runtime:

add(true, false);

To resolve this, you can use the TypeScript union type. The union type allows
you to combine multiple types into one type.

For example, the following variable is of type number or string:

let result: number | string;

result = 10; // OK

result = 'Hi'; // also OK

result = false; // a boolean value, not OK

A union type describes a value that can be one of several types, not just two. For
example number | string | boolean is the type of a value that can be a number, a
string, or a boolean.

Back to the add() function example, you can change the types of parameters from
the any to a union like this:

function add(a: number | string, b: number | string) {

if (typeof a === 'number' && typeof b === 'number') {

return a + b;

}
if (typeof a === 'string' && typeof b === 'string') {

return [Link](b);

throw new Error('Parameters must be numbers or strings');

We can specify the union type for the add function:

function add(a: number | string, b: number | string) : number | string {

if (typeof a === 'number' && typeof b === 'number') {

return a + b;

if (typeof a === 'string' && typeof b === 'string') {


return [Link](b);

QA Mitra – One Stop Shop for QA


}

throw new Error('Parameters must be numbers or strings');

Summary

 A TypeScript union type allows you to store a value of one or several types in
a variable.

TypeScript never Type


Summary: in this section, you will learn about the TypeScript never type to represent
a value that never occurs.
Introduction to the TypeScript never type

In TypeScript, a type is like a set of values. For example, the number type holds the
numbers 1, 2, 3, etc. The string type holds the strings like 'Hi', 'Hello', etc.
The null type holds a single value, which is null.
The never type is a type that holds no value. It is like an empty set.

Since a never type does not hold any value, you cannot assign a value to a variable
with the never type.

For example, the following will result in an error:


let empty: never = 'hello';

The TypeScript compiler issues the following error:

Type 'string' is not assignable to type ‘never’)


So why do we need the never type in the first place?
Since the never type has zero value, you can use it to denote an impossibility in the
type system.

For example, you may have an intersection type that can be both a string and a
number at the same time, which is impossible:

type Alphanumeric = string & number; // never

Therefore, the TypeScript compiler infers the type of Alphanumeric as never.

This is because string and number are mutually exclusive. In other words, a value
cannot be both a string and a number simultaneously.

QA Mitra – One Stop Shop for QA


Typically, you use the never type to represent the return type of a function that never
returns the control to the caller. For example, a function that always throws an error:

function raiseError(message: string): never {


throw new Error(message);

Please do not confuse with functions that return void but still return the control to the
caller.

If you have a function that contains an indefinite loop, its return type should be never.
For example:

function forever(): never {

while (true) {}

In this example, the type of the return type of the forever() function is never.

The TypeScript never example

Let’s take an example of using the never type:

type Role = 'admin' | 'user';

const authorize = (role: Role): string => {

switch (role) {

case 'admin':

return 'You can do anything';

case 'user':

return 'You can do something';


default:

// never reach here util we add a new role

const _unreachable: never = role;

throw new Error(`Invalid role: ${_unreachable}`);

};

QA Mitra – One Stop Shop for QA


[Link](authorize('admin'));

How it works.

Step 1. Define a type Role that can be either a string 'admin' or 'user':

type Role = 'admin' | 'user';

Step 2. Create the authorize() function that accepts a value of the Role type and
returns a string:

const authorize = (role: Role): string => {

switch (role) {

case 'admin':

return 'You can do anything';

case 'user':

return 'You can do something';

default:

// never reach here util we add a new role

const _unreachable: never = role;

throw new Error(`Invalid role: ${_unreachable}`);

}
};

Summary

 Use the never type that holds no value, denoting an impossibility in the type
system.

QA Mitra – One Stop Shop for QA


Control Flow Statements In TypeScript

TypeScript if else
Summary: in this section, you will learn about the TypeScript if...else statement.

TypeScript if statement

An if statement executes a statement based on a condition. If the condition is truthy,


the if statement will execute the statements inside its body:

if(condition) {

// if-statement

For example, the following statement illustrates how to use the if statement to
increase the counter variable if its value is less than the value of the max constant:

const max = 100;

let counter = 0;

if (counter < max) {

counter++;

[Link](counter); // 1

Output:

1
In this example, because the counter variable starts at zero, it is less than
the max constant. The expression counter < max evaluates to true therefore
the if statement executes the statement counter++.

Let’s initialize the counter variable to 100:

const max = 100;


let counter = 100;

QA Mitra – One Stop Shop for QA


if (counter < max) {

counter++;

[Link](counter); // 100

Output:

100
In this example, the expression counter < max evaluates to false. The if statement
doesn’t execute the statement counter++. Therefore, the output is 100.

TypeScript if…else statement

If you want to execute other statements when the condition in the if statement
evaluates to false, you can use the if...else statement:
Syntax:-

if(condition) {

// if-statements

} else {

// else statements;

}
The following illustrates an example of using the if..else statement:

const max = 100;

let counter = 100;

if (counter < max) {

counter++;

} else {

counter = 1;
}

[Link](counter);

QA Mitra – One Stop Shop for QA


Output:

In this example, the expression counter < max evaluates to false therefore the
statement in the else branch executes that resets the counter variable to 1.

TypeScript if…else if…else statement

When you want to execute code based on multiple conditions, you can use
the if...else if...else statement.

The if…else if…else statement can have one or more else if branches but only
one else branch.

For example:

let discount: number;

let itemCount = 11;

if (itemCount > 0 && itemCount <= 5) {

discount = 5; // 5% discount

} else if (itemCount > 5 && itemCount <= 10) {

discount = 10; // 10% discount

} else {

discount = 15; // 15%

[Link](`You got ${discount}% discount. `)

Output:
You got 15% discount.

This example used the if...else if...else statement to determine the discount based on
the number of items.

If the number of items is less than or equal to 5, the discount is 5%. The statement in
the if branch executes.

If the number of items is less than or equal to 10, the discount is 10%. The statement
in the else if branch executes.

QA Mitra – One Stop Shop for QA


When the number of items is greater than 10, the discount is 15%. The statement in
the else branch executes.

In this example, the assumption is that the number of items is always greater than
zero. However, if the number of items is less than zero or greater than 10, the
discount is 15%.

To make the code more robust, you can use another else if instead of
the else branch like this:

let discount: number;

let itemCount = 11;

if (itemCount > 0 && itemCount <= 5) {

discount = 5; // 5% discount

} else if (itemCount > 5 && itemCount <= 10) {

discount = 10; // 10% discount

} else if (itemCount > 10) {

discount = 15; // 15%

} else {

throw new Error('The number of items cannot be negative!');


}

[Link](`You got ${discount}% discount. `);

Output:

You got 15% discount.

In this example, when the number of items is greater than 10, the discount is 15%.
The statement in the second else if branch executes.

If the number of items is less than zero, the statement in the else branch executes.

Summary
 Use the if statement to execute code based on a condition.

 Use if else if...else statement to execute code based on multiple conditions.

QA Mitra – One Stop Shop for QA


TypeScript switch case
Summary: in this section, you will about the TypeScript switch...case statement.

Introduction to TypeScript switch case statement

The following shows the syntax of the switch...case statement:


switch ( expression ) {

case value1:

// statement 1

break;

case value2:

// statement 2

break;
case valueN:

// statement N

break;

default:

//

break;

How it works:
First, the switch...case statement evaluates the expression.

Then, it searches for the first case clause whose expression evaluates to the same
value as the value (value1, value2, …valueN).

The switch...case statement will execute the statement in the first case clause whose
value matches.

If no matching case clause is found, the switch...case statement looks for the
optional default clause. If the default clause is available, it executes the statement in
the default clause.

The break statement that associates with each case clause ensures that the control
breaks out of the switch...case statement once the statements in the case clause
complete.

QA Mitra – One Stop Shop for QA


If the matching case clause doesn’t have the break statement, the program
execution continues at the next statement in the switch...case statement.

By convention, the default clause is the last clause in the switch...case statement.
However, it doesn’t need to be so.

TypeScript switch case statement examples

Let’s take some examples of using the switch...case statement.

1) A simple TypeScript switch case example

The following example shows a simple switch...case example that shows a message
based on the target id:

let targetId = 'btnDelete';

switch (targetId) {

case 'btnUpdate':

[Link]('Update');

break;

case 'btnDelete':

[Link]('Delete');

break;

case 'btnNew':

[Link]('New');

break;

Output:
Delete

In this example, the targetId is set to btnDelete.

The switch...case statement compares the targetId with a list of values. Because
the targetId matches the 'btnDelete' the statement in the corresponding case clause
executes.

2) Grouping case example

If you have a code that is shared by multiple cases, you can group them. For
example:

QA Mitra – One Stop Shop for QA


// change the month and year

let month = 2,

year = 2020;

let day = 0;

switch (month) {

case 1:
case 3:

case 5:

case 7:

case 8:

case 10:

case 12:

day = 31;

break;

case 4:

case 6:

case 9:

case 11:

day = 30;
break;

case 2:
// leap year

if (((year % 4 == 0) &&

!(year % 100 == 0))

|| (year % 400 == 0))

day = 29;
else

QA Mitra – One Stop Shop for QA


day = 28;

break;

default:

throw Error('Invalid month');

[Link](`The month ${month} in ${year} has ${day} days`);

Output:
The month 2 in 2020 has 29 days

This example returns the days of a specific month and year.

If the month is 1,3, 5, 7, 8, or 12, the number of days is 31. If the month is 4, 6, 9, or
11, the number of days is 30.

If the month is 2 and the year is a leap year, it returns 29 days, otherwise, it returns
28 days.

Loops In TypeScript

1. For Loop

A for loop repeats a block of code a specific number of times. It’s typically used when
you know how many iterations you want in advance.
Definition:

 Initialization: The loop starts by initializing one or more loop counters.

 Condition: The loop checks this condition before each iteration. If it's true, the
loop executes. If it's false, the loop ends.
 Increment/Decrement: After each loop iteration, the counter variable is
updated (either incremented or decremented).

Syntax:

for (initialization; condition; increment/decrement) {


// Code to be executed

QA Mitra – One Stop Shop for QA


}
Example:

for (let i = 0; i < 5; i++) {

[Link]("Iteration number:", i);

2. While Loop

A while loop repeats as long as a specified condition is true. It’s useful when you
don't know how many iterations you need, but you want the loop to run based on a
condition.
Definition:

 The loop continues to execute the block of code while the condition is true.
Once the condition becomes false, the loop ends.

Syntax:

while (condition) {

// Code to be executed

}
Example:

let i = 0;

while (i < 3) {

[Link]("While loop iteration:", i);


i++;

Real time use case:

1. You need to add items to the cart until it reaches a specific count.

Example:

QA Mitra – One Stop Shop for QA


Scenario: You want to add products to the cart until there are exactly 5 items in the
cart. If there are fewer than 5 items, keep adding more items.

let itemCount = await [Link]('.cart-count').innerText();


while (parseInt(itemCount) < 5) {

await [Link]('.add-to-cart-btn'); // Add item to cart

[Link](`Current cart count: ${itemCount}`);

itemCount = await [Link]('.cart-count').innerText();

[Link]('Added 5 items to the cart.');

3. Do-While Loop

A do-while loop is similar to the while loop, except that it guarantees the loop will run
at least once before the condition is checked.
Detailed Definition:

 The block of code inside the do will execute once before the condition is
evaluated, making it useful for situations where you want the code to run at
least once, no matter what.
Syntax:

do {

// Code to be executed

} while (condition);

Example:

let i = 0;

do {

[Link]("Do-while iteration:", i);


i++;

QA Mitra – One Stop Shop for QA


} while (i < 2);

Real time use case:

Example:

Do-While Loop

In real-time sometimes you may need to keep prompting the user for their password
until they enter the correct one.
Use Case: Prompting a user to enter a valid password

let enteredPassword;

do {

enteredPassword = prompt("Enter your password:");

if (validatePassword(enteredPassword)) {

[Link]("Access granted.");

} else {

[Link]("Invalid password, try again.");

}
} while (!validatePassword(enteredPassword));

4. For...of Loop

The for...of loop iterates over the values of iterable objects like arrays, strings, maps,
and sets.
Detailed Definition:

 Instead of using a counter, for...of directly gives you the values from the
iterable object.
Syntax:

for (variable of iterable) {


// Code to be executed

QA Mitra – One Stop Shop for QA


}
Example:

const fruits = ["Apple", "Banana", "Orange"];

for (let fruit of fruits) {

[Link](fruit);

 This loop will print each fruit in the array.

Real time Use Case:

 Processing elements in an array: For instance, when you want to iterate


through an array of product names or items in a shopping cart

const cart = ["Shoes", "Shirt", "Hat"];

for (let item of cart) {

[Link](`Checking out: ${item}`);

5. For...in Loop

The for...in loop iterates over the properties of an object (including inherited
properties).
Detailed Definition:

 It loops over the enumerable properties of an object, providing access to the


property names (keys).
Syntax:

for (variable in object) {

// Code to be executed

Example:

const car = { make: "Toyota", model: "Camry", year: 2020 };

for (let key in car) {


[Link](key, car[key]);

QA Mitra – One Stop Shop for QA


}

Real time Use Case:

 Iterating over object properties: Often used when you need to extract and
process information from an object, such as an API response.

const user = { name: "Alice", age: 30, email: "alice@[Link]" };

for (let key in user) {

[Link](`${key}: ${user[key]}`);

Functions In TypeScript

TypeScript Functions
Summary: in this section, you will learn about the TypeScript functions and how to
use type annotations to enforce the type checks for functions.

Introduction to TypeScript functions

TypeScript functions are the building blocks of readable, maintainable, and reusable
code.

Like JavaScript, you use the function keyword to declare a function in TypeScript:

function name(parameter: type, parameter:type,...): returnType {

// do something
}

Unlike JavaScript, TypeScript allows you to use type annotations in parameters and
return the value of a function.
Let’s see the following add() function example:

function add(a: number, b: number): number {

return a + b;

}
In this example, the add() function accepts two parameters with the number type.

QA Mitra – One Stop Shop for QA


When you call the add() function, the TypeScript compiler will check each argument
passed to the function to ensure that they are numbers.

In the add() function example, you can only pass numbers into it, not the values of
other types.

The following code will result in an error because it passes two strings instead of two
numbers into the add() function:

let sum = add('10', '20');

Error:
error TS2345: Argument of type '"10"' is not assignable to parameter of type
'number'

The types of function parameters are also available within the function body for type
checking.

The : number after the parentheses indicate the return type. The add() function
returns a value of the number type in this case.

When a function has a return type, the TypeScript compiler checks


every return statement against the return type to ensure that the return value is
compatible with it.

If a function does not return a value, you can use the void type as the return type.
The void keyword indicates that the function doesn’t return any value. For example:

function echo(message: string): void {

[Link]([Link]());

The void prevents the code inside the function from returning a value and stops the
calling code from assigning the result of the function to a variable.

When you do not annotate the return type, TypeScript will try to infer an appropriate
type. For example:

function add(a: number, b: number) {


return a + b;

In this example, the TypeScript compiler tries to infer the return type of
the add() function to the number type, which is expected.

Summary

QA Mitra – One Stop Shop for QA


 Use type annotations for function parameters and return type to keep the
calling code inline and ensure the type checking within the function body.

Types Of Functions in TypeScript


1. Named function:

A Named Function is one that we write in code and then use whenever we need it by
referencing its name and providing it with some parameters. Named functions come
in handy when we need to call a function several times to give various values to it or
run it multiple times.
function add(a:number, b:number) : number {

return a + b;
}

[Link](add(5, 4));

Output

9
2. Anonymous function:

We can define a function in TypeScript without giving it a name. This nameless


function is referred to as the Anonymous Function. A variable must be assigned to
an anonymous function.

let add = function (a:number, b:number) :number{

return a + b;

}
[Link](add(5, 4));

Output

Function Declaration

QA Mitra – One Stop Shop for QA


Function Declaration is the traditional way to define a function. It is somehow similar
to the way we define a function in other programming languages. We start declaring
using the keyword “function”. Then we write the function name and the parameters.
Example: Below is an example that illustrates the use of Function Declaration.

// Function declaration

function add(a:number, b:number) :number {

[Link](a + b);

// Calling a function
add(2, 3);

Output

After defining a function, we call it whenever the function is required.

Function Expression

Function Expression is another way to define a function in TypeScript. Here we


define a function using a variable and store the returned value in that variable.

Example: Below is an example that illustrates the use of Function Expression.

// Function Expression

const add = function (a:number, b:number) : number{

[Link](a + b);

// Calling function

add(2, 3);

QA Mitra – One Stop Shop for QA


Output

Here, the whole function is an expression and the returned value is stored in the
variable. We use the variable name to call the function.

Arrow Function:

It is used to shorten the code. Here we do not use the “function” keyword and use
the arrow symbol.
Example: Below is the example that illustrates the use of the Arrow Function.

// Single line of code

let add = (a:number, b:number) : number => a + b;{}

[Link](add(3, 2));

Output

This shortens the code to a single line compared to other approaches. In a single
line of code, the function returns implicitly.
Note: When there is a need to include multiple lines of code we use brackets. Also,
when there are multiple lines of code in the bracket we should write return explicitly
to return the value from the function.
Example: This is an example with multiple lines of code in arrow function

// Multiple line of code


const great = (a:number, b:number):string => {

if (a > b)

return "a is greater";

else

QA Mitra – One Stop Shop for QA


return "b is greater";

[Link](great(3, 5));

Output

b is greater

QA Mitra – One Stop Shop for QA

You might also like