SlideShare a Scribd company logo
1 of 80
Click to edit Master title style
1
Typescript
Click to edit Master title style
2
Introduction to TypeScript
• TypeScript is a super set 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.
• TypeScript files use the .ts extension rather than the .js extension of
JavaScript files.
2
Click to edit Master title style
3 3
• The following diagram shows the relationship between
TypeScript and JavaScript:
Click to edit Master title style
4 4
• TypeScript introduced a great deal of syntax taken from object-oriented programming,
including but not limited to:
• interfaces,
• classes,
• enumerated types,
• generics,
• modules.
• abstract classes or access modifiers are still nowhere to be found in JavaScript, while
TypeScript has them.
Click to edit Master title style
5
Advantages
5
• TypeScript is an open-source language with continuous development and
maintenance by Microsoft.
• TypeScript runs on any browser or JavaScript engine.
• TypeScript is similar to JavaScript and uses the same syntax and semantics.
All of TypeScript's code finally gets converted into JavaScript. This allows a
quicker learning curve for front-end developers currently coding in JavaScript.
• TypeScript is also closer in syntax to backend languages like Java and Scala.
This helps backend developers write front-end code faster.
Click to edit Master title style
6
Basic typescript program
6
let message: string = 'Hello, World!';
console.log(message);
Example 2 –
function addNumbers(a: number, b: number) {
return a + b;
}
var sum: number = addNumbers(10, 15)
console.log('Sum of the two numbers is: ' +sum);
Click to edit Master title style
7
Datatypes
7
• Number type – it is used to declare a variable that holds a number.
Syntax –
let price : number = 20;
let price : number = 3.5;
• String 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.
let description = `This TypeScript string can
span multiple lines`;
Click to edit Master title style
8 8
• Boolean Types - The TypeScript boolean type allows two values: true and
false. It’s one of the primitive types in TypeScript.
let pending: boolean;
pending = true;
Click to edit Master title style
9 9
• Array - 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[];
• let skills = ['Problem Sovling','Software Design','Programming'];
• TypeScript arrays can access the properties and methods of a JavaScript.
• Example
• let series = [1, 2, 3];
• console.log(series.length); // 3
Click to edit Master title style
10
10
• Array indices and length
Click to edit Master title style
11
Any type
11
• Sometimes, you may need to store a value in a variable.
• Any type can handle any values.
• To do so, you use the any type. The any type allows you to assign a value
of any type to a variable:
• Use the any type to store a value that you don’t actually know its type at
the compile-time
Click to edit Master title style
12
12
Click to edit Master title style
13
Introduction to TypeScript object type
13
• The following are primitive types in TypeScript:
• number
• bigint
• string
• boolean
• null
• undefined
The TypeScript object type represents all values that are not in primitive types.
Click to edit Master title style
14
14
Void - Generally used on function return-types
Declaring variables of type void is not useful because you can only assign null
Null - It is used when an object does not have any value
Undefined - Denotes value given to uninitialized variable
In TypeScript, both undefined and null actually have their types named undefined
and null respectively. Much like void, they’re not extremely useful on their own:
By default null and undefined are subtypes of all other types. That means you can
assign null and undefined to something like number.
Click to edit Master title style
15
Enum
15
• Enums or enumerations are a new data type supported in TypeScript.
• In simple words, enums allow us to declare a set of named constants i.e. a
collection of related values that can be numeric or string values.
• There are three types of enums:
• Numeric enum
• String enum
• Heterogeneous enum
• Numeric ENum - Numeric enums are number-based enums i.e. they store string
values as numbers.
• Enums can be defined using the keyword enum.
Click to edit Master title style
16
16
• Examle numeric enum -
• enum PrintMedia {
• Newspaper,
• Newsletter,
• Magazine,
• Book
• }
In the above example, we have an enum named PrintMedia. The enum has four values: Newspaper,
Newsletter, Magazine, and Book. Here, enum values start from zero and increment by 1 for each member.
Newspaper = 0
Newsletter = 1
Magazine = 2
Book = 3
Enums are always assigned numeric values when they are stored. The first value always takes the numeric
value of 0, while the other values in the enum are incremented by 1.
Click to edit Master title style
17
17
• We also have the option to initialize the first numeric value ourselves. For example, we can
write the same enum as:
• enum PrintMedia {
• Newspaper = 1,
• Newsletter,
• Magazine,
• Book
• }
• The first member, Newspaper, is initialized with the numeric value 1. The remaining members
will be incremented by 1 from the numeric value of the first value. Thus, in the above
example, Newsletter would be 2, Magazine would be 3 and Book would be 4.
Click to edit Master title style
18
String Enum
18
• String enums are similar to numeric enums, except that the enum values are initialized with string
values rather than numeric values.
• The benefits of using string enums is that string enums offer better readability.
enum PrintMedia {
Newspaper = "NEWSPAPER",
Newsletter = "NEWSLETTER",
Magazine = "MAGAZINE",
Book = "BOOK"
}
// Access String Enum
PrintMedia.Newspaper; //returns NEWSPAPER
PrintMedia['Magazine']; //returns MAGAZINE
Click to edit Master title style
19
19
• In the example, we have defined a string enum, PrintMedia, with the
same values as the numeric enum above, with the difference that
these enum values are initialized with string literals.
• The difference between numeric and string enums is that numeric
enum values are auto-incremented, while string enum values need to
be individually initialized.
Click to edit Master title style
20
Heterogenous Enum
20
• Heterogeneous enums are enums that contain both string and numeric values.
Example –
enum Status {
Active = 'ACTIVE',
Deactivate = 1,
Pending
}
Click to edit Master title style
21
Tuples
21
• TypeScript introduced a new data type called Tuple. Tuple can contain two values of
different data types.
• example of number, string and tuple type variables.
var empId: number = 1;
var empName: string = "Steve";
// Tuple type variable
var employee: [number, string] = [1, "Steve"];
In the above example, we have defined a variable empId as number type and empName
as string type with values.
Here, we declared and assigned two variables to id and name of an employee.
employee is the tuple type variable with two values of number and string type.
Click to edit Master title style
22
22
• A tuple type variable can include multiple data types as shown below.
• var employee: [number, string] = [1, "Steve"];
• var person: [number, string, boolean] = [1, "Steve", true];
You can declare an array of tuple also.
• var employee: [number, string][];
• employee = [[1, "Steve"], [2, "Bill"], [3, "Jeff"]];
• Accessing Tuple Elements
• We can access tuple elements using index, the same way as an array. An index starts from zero.
• var employee: [number, string] = [1, "Steve"];
• employee[0]; // returns 1
• employee[1]; // returns "Steve"
Click to edit Master title style
23
How to declare object
23
• 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'
};
console.log(employee);
Click to edit Master title style
24
Functions in Typescript
24
• A function definition specifies what and how a
specific task would be done.
• A function must be called so as to execute it.
• Functions may also return value along with
control, back to the caller.
• Parameters are a mechanism to pass values
to functions.
Syntax
function function_name (param1[:type], param2[:type], param3[:type])
Click to edit Master title style
25
Named Functions
25
• A named function is one where you declare and call a function by its given name.
function display() {
console.log("Hello TypeScript!");
}
display(); //Output: Hello TypeScript
Functions can also include parameter types and return type.
function Sum(x: number, y: number) : number {
return x + y;
}
Sum(2,3); // returns 5
Click to edit Master title style
26
Anonymous Functions
26
• An anonymous function is one which is defined as an expression.
• This expression is stored in a variable. So, the function itself does not have a name.
• These functions are invoked using the variable name that the function is stored in.
let greeting = function() {
console.log("Hello TypeScript!");
};
greeting(); //Output: Hello TypeScript!
An anonymous function can also include parameter types and return type.
let Sum = function(x: number, y: number) : number
{
return x + y;
}
Sum(2,3); // returns 5
Click to edit Master title style
27
Optional Parameters
27
• Optional parameters can be used when arguments
need not be compulsorily passed for a function’s
execution.
• Parameter can be marked optional by appending (?)
question mark to its name.
Example
Normal function –
function function_name (param1[:type], param2[:type], param3[:type])
Optional Function –
function function_name (param1[:type], param2[:type], param3 ?[:type])
Click to edit Master title style
28
Default Parameters
28
• Function parameters can also be assigned values by default.
• such parameters can also be explicitly passed values
Syntax –
function function_name(param1[:type],param2[:type] = default_value) {
}
Note − A parameter cannot be declared optional and default at the same time.
Click to edit Master title style
29
Arrow Functions
29
• Fat arrow notations are used for anonymous functions i.e for function expressions.
They are also called lambda functions in other languages.
Syntax –
(param1, param2, ..., paramN) => expression
Using fat arrow =>, we dropped the need to use the function keyword.
Parameters are passed in the parenthesis (), and the function expression is enclosed
within the curly brackets { }.
let sum = (x: number, y: number): number => {
return x + y;
}
sum(10, 20); //returns 30
Click to edit Master title style
30
Rest Parameters
30
• TypeScript introduced rest parameters to accommodate n number of
parameters easily.
• When the number of parameters that a function will receive is not known or can
vary, we can use rest parameters.
• TypeScript, we can use the rest parameter denoted by ellipsis ...
• We can pass zero or more arguments to the rest parameter.
• function Greet(greeting: string, ...names: string[]) {
• return greeting + " " + names.join(", ") + "!";
• }
Greet("Hello", "Steve", "Bill"); // returns "Hello Steve, Bill!"
• Greet("Hello");// returns "Hello !"
Click to edit Master title style
31
Control Flow Statement
31
• IF …Else statement
• What is 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
Syntax-
if(condition) {
// if-statement
}
Click to edit Master title style
32
If…else Statment
32
• 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;
}
Click to edit Master title style
33
33
Click to edit Master title style
34
If…else if…else statment
34
• 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.
Click to edit Master title style
35
Ternary Operator
35
• A ternary operator is denoted by '?' and is used as a short
cut for an if..else statement.
• It checks for a boolean condition and executes one of the
two statements, depending on the result of the boolean
condition.
Syntax
Boolean expression? First statement : second statement
Example
let x: number = 10, y = 20;
x > y? console.log('x is greater than y.') : console.log('x is less than or equal to y.')
Click to edit Master title style
36
36
Click to edit Master title style
37
Switch
37
• The switch statement is used to check for multiple values and executes sets of statements
for each of those values.
• A switch statement has one block of code corresponding to each value and can have any
number of such blocks.
• When the match to a value is found, the corresponding block of code is executed.
Click to edit Master title style
38
Switch
38
Click to edit Master title style
39
39
Syntax –
switch(expression) {
case constant-expression1: {
//statements;
break;
}
case constant_expression2: {
//statements;
break;
}
default: {
//statements;
break;
}
}
Click to edit Master title style
40
40
• The following rules are applied on the switch statement:
• The switch statement can include constant or variable expression which
can return a value of any data type.
• There can be any number of case statements within a switch. The case
can include a constant or an expression.
• We must use break keyword at the end of each case block to stop the
execution of the case block.
• The return type of the switch expression and case expression must
match.
• The default block is optional.
Click to edit Master title style
41
41
• Example –
let day : number = 4;
switch (day) {
case 0:
console.log("It is a Sunday.");
break;
case 1:
console.log("It is a Monday.");
break;
case 2:
console.log("It is a Tuesday.");
break;
default:
console.log("No such day exists!");
break;
}
Click to edit Master title style
42
TypeScript - for Loops
42
• TypeScript supports the following for loops:
• for loop
• for..of loop
• for..in loop
Click to edit Master title style
43
For loop
43
• The for loop is used to execute a block of code a given number of times,
which is specified by a condition.
Syntax
for (first expression; second expression; third expression ) {
// statements to be executed repeatedly
}
the first expression is executed before the loop starts.
The second expression is the condition for the loop to execute.
And the third expression is executed after the execution of every code
block.
Click to edit Master title style
44
44
Click to edit Master title style
45
For…of Loop
45
• TypeScript includes the for...of loop to iterate and access elements of an array
• The for...of loop can also return a character from a string value.
Example –
let str = "Hello World";
for (var char of str) {
console.log(char); // prints chars: H e l l o W o r l d
}
Example –
let arr = [10, 20, 30, 40];
for (var val of arr) {
console.log(val); // prints values: 10, 20, 30, 40
}
Click to edit Master title style
46
For…in Loop
46
• Another form of the for loop is for...in. This can be used with an array.
• The for...in loop iterates through a list or collection and returns an index on each iteration.
Example
let arr = [10, 20, 30, 40];
for (var index in arr) {
console.log(index); // prints indexes: 0, 1, 2, 3
console.log(arr[index]); // prints elements: 10, 20, 30, 40
}
Click to edit Master title style
47
Typescript While Loop
47
• The while loop is another type of loop that checks for a specified condition
before beginning to execute the block of statements.
• The loop runs until the condition value is met.
Syntax –
while (condition expression) {
// code block to be executed
}
The condition expression checks for a specified condition before running the
block of code.
Example –
let i: number = 2;
while (i < 4) {
console.log( "Block statement execution no." + i )
i++; }
Click to edit Master title style
48
Do…while loop
48
• The do..while loop is similar to the while loop, except that the condition is given at the end
of the loop.
• The do..while loop runs the block of code at least once before checking for the specified
condition.
• For the rest of the iterations, it runs the block of code only if the specified condition is met.
Syntax-
do {
// code block to be executed
}
while (condition expression);
Click to edit Master title style
49
49
• Example –
let i: number = 2;
do {
console.log("Block statement execution no." + i )
i++;
} while ( i < 4)
Click to edit Master title style
50
Interface
50
• Interface is a structure that defines the contract in your application. It
defines the syntax for classes to follow.
• Classes that are derived from an interface must follow the structure
provided by their interface.
• The TypeScript uses interface for type checking. This is also known as
"duck typing" or "structural subtyping".
• An interface is defined with the keyword interface and it can include
properties and method declarations using a function
Click to edit Master title style
51
51
Interface example
interface IEmployee {
empCode: number;
empName: string;
getSalary: (number) => number; // arrow function
getManagerName(number): string;
}
the IEmployee interface includes two properties empCode and empName. It also includes a
method declaration getSalaray using an arrow function which includes one number
parameter and a number return type.
The getManagerName method is declared using a normal function. This means that any
object of type IEmployee must define the two properties and two methods.
Click to edit Master title style
52
Interface as type
52
• Interface in TypeScript can be used to define a type and also to implement it in the class.
• The following interface IEmployee defines a type of a variable.
Example
interface KeyPair {
key: number;
value: string;
}
let kv1: KeyPair = { key:1, value:"Steve" }; // OK
let kv2: KeyPair = { key:1, val:"Steve" }; // Compiler Error: 'val' doesn't exist in type 'KeyPair'
let kv3: KeyPair = { key:1, value:100 }; // Compiler Error:
Click to edit Master title style
53
Interface as Function Type
53
• TypeScript interface is also used to define a type of a function. This ensures the function
signature.
interface KeyValueProcessor
{
(key: number, value: string): void;
};
function addKeyValue(key:number, value:string):void {
console.log('addKeyValue: key = ' + key + ', value = ' + value)
}
let kvp: KeyValueProcessor = addKeyValue;
kvp(1, 'Bill'); //Output: addKeyValue: key = 1, value = Bill
Click to edit Master title style
54
54
interface Person { firstName: string; lastName: string; }
function getFullName(person: Person) {
return `${person.firstName} ${person.lastName}`;
}
let john = {
firstName: 'John',
lastName: 'Doe'
};
console.log(getFullName(john));
Click to edit Master title style
55
55
let format: StringFormat;
format = function (str: string, isUpper: boolean) {
return isUpper ? str.toLocaleUpperCase() : str.toLocaleLowerCase();
};
console.log(format('hi', false));
interface StringFormat {
(str: string, isUpper: boolean): string
}
Click to edit Master title style
56
Classes
56
• In object-oriented programming languages like Java and C#, classes are
the fundamental entities used to create reusable components.
• Functionalities are passed down to classes and objects are created from
classes.
• TypeScript introduced classes to avail the benefit of object-oriented
techniques like encapsulation and abstraction. The class in TypeScript is
compiled to plain JavaScript functions by the TypeScript compiler to work
across platforms and browsers.
• A class can include the following:
• Constructor
• Properties
• Methods
Click to edit Master title style
57
Class example
57
class Employee {
empCode: number;
empName: string;
constructor(code: number, name: string) {
this.empName = name;
this.empCode = code;
}
getSalary() : number {
return 10000;
}
}
Click to edit Master title style
58
Constructor
58
• The constructor is a special type of method which is called when creating an object. In
TypeScript, the constructor method is always defined with the name "constructor".
Example –
class Employee {
empCode: number;
empName: string;
constructor(empcode: number, name: string ) {
this.empCode = empcode;
this.name = name;
}
}
Click to edit Master title style
59
59
• In the example, the Employee class includes a constructor with the parameters
empcode and name. In the constructor, members of the class can be accessed
using this keyword e.g. this.empCode or this.name.
• It is not necessary for a class to have a constructor.
Click to edit Master title style
60
Creating object of class
60
• An object of the class can be created using the new keyword.
class Employee {
empCode: number;
empName: string;
}
let emp = new Employee();
Here, we create an object called emp of type Employee using let emp = new Employee();. The above
class does not include any parameterized constructor so we cannot pass values while creating an
object.
If the class includes a parameterized constructor, then we can pass the values while creating the
object.
Click to edit Master title style
61
Inheritance in class
61
• Just like object-oriented languages such as Java and C#, TypeScript classes can be
extended to create new classes with inheritance, using the keyword extends.
• The key to understanding Inheritance is that it provides code re-usability. In place of writing
the same code, again and again, we can simply inherit the properties of one class into the
other.
• along with the inherited properties and methods, a child class can have its own properties
and methods.
• We must call super() method first before assigning values to properties in the constructor of
the derived class.
Click to edit Master title style
62
62
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
empCode: number;
constructor(empcode: number, name:string) {
super(name);
this.empCode = empcode;
}
displayName():void {
console.log("Name = " + this.name + ", Employee Code = " + this.empCode);
}
}
let emp = new Employee(100, "Bill");
emp.displayName();
Click to edit Master title style
63
Class implements interface
63
• A class can implement single or multiple interfaces.
interface IPerson {
name: string;
display():void;
}
interface IEmployee {
empCode: number;
}
class Employee implements IPerson, IEmployee {
empCode: number;
name: string;
constructor(empcode: number, name:string) {
this.empCode = empcode;
this.name = name;
}
Click to edit Master title style
64
64
display(): void {
console.log("Name = " + this.name + ", Employee Code = " +
this.empCode);
}
}
let per:IPerson = new Employee(100, "Bill");
per.display(); // Name = Bill, Employee Code = 100
let emp:IEmployee = new Employee(100, "Bill");
emp.display(); //Compiler Error: Property 'display' does not exist on type
'IEmployee'
Click to edit Master title style
65
Method Overriding
65
• When a child class defines its own implementation of a method from the parent
class, it is called method overriding.
• the children classes have a method of the same name as that of the parent
class.
Click to edit Master title style
66
TypeScript - Data Modifiers
66
• In object-oriented programming, the concept of 'Encapsulation' is used to
make class members public or private i.e. a class can control the visibility
of its data members. This is done using access modifiers.
• There are three types of access modifiers in TypeScript: public, private
and protected.
• Public
• Private
• Protected
Click to edit Master title style
67
Public – Data modifiers
67
• By default, all members of a class in TypeScript are public. All the public
members can be accessed anywhere without any restrictions.
Example – class Employee {
public empCode: string;
empName: string;
}
let emp = new Employee();
emp.empCode = 123;
emp.empName = "Swati";
In the above example, empCode and empName are declared as public. So,
they can be accessible outside of the class using an object of the class.
notice that there is not any modifier applied before empName, as TypeScript
treats properties and methods as public by default if no modifier is applied to
them.
Click to edit Master title style
68
Private Data modifiers
68
• The private access modifier ensures that class members are visible only to that class and
are not accessible outside the containing class.
class Employee {
private empCode: number;
empName: string;
}
let emp = new Employee();
emp.empCode = 123; // Compiler Error
emp.empName = "Swati";//OK
In the above example, we have marked the member empCode as private. Hence, when we
create an object emp and try to access the emp.empCode member, it will give an error.
Click to edit Master title style
69
Protected
69
• The protected access modifier is similar to the private access modifier, except that protected
members can be accessed using their deriving classes.
•
Click to edit Master title style
70
Typescript – Read Only
70
• TypeScript includes the readonly keyword that makes a property as read-only in the class or
interface.
• Prefix readonly is used to make a property as read-only. Read-only members can be accessed
outside the class, but their value cannot be changed.
• Since read-only members cannot be changed outside the class, they either need to be
initialized at declaration or initialized inside the class constructor.
Click to edit Master title style
71
71
• Example –
class Employee {
readonly empCode: number;
empName: string;
constructor(code: number, name: string) {
this.empCode = code;
this.empName = name;
}
}
let emp = new Employee(10, "John");
emp.empCode = 20; //Compiler Error
emp.empName = 'Bill';
In the above example, we have the Employee class with two properties- empName and empCode.
Since empCode is read only, it can be initialized at the time of declaration or in the constructor.
If we try to change the value of empCode after the object has been initialized, the compiler shows
the following compilation error:
Click to edit Master title style
72
Var , Let and Const
72
• Scope essentially means where these variables are available for use. var declarations are
globally scoped or function/locally scoped.
• The scope is global when a var variable is declared outside a function. This means that any
variable that is declared with var outside a function block is available for use in the whole
window.
• var is function scoped when it is declared within a function. This means that it is available and
can be accessed only within that function.
Example –
var tester = "hey hi";
function newFunction() {
var hello = "hello";
}
console.log(hello); // error: hello is not defined
Click to edit Master title style
73
73
• Var Variables can be re-declared and updated
Example –
var greeter = "hey hi";
var greeter = "say Hello instead";
Click to edit Master title style
74
Let
74
• A block is a chunk of code bounded by {}. A block lives in curly braces.
Anything within curly braces is a block.
• So a variable declared in a block with let is only available for use
within that block.
let greeting = "say Hi";
let times = 4;
if (times > 3) {
let hello = "say Hello instead";
console.log(hello);// "say Hello instead"
}
console.log(hello) // hello is not defined
Click to edit Master title style
75
75
• let can be updated but not re-declared.
• Just like var, a variable declared with let can be updated within its scope.
Unlike var, a let variable cannot be re-declared within its scope. So while
this will work:
let greeting = "say Hi";
greeting = "say Hello instead";
This will return an error –
let greeting = "say Hi";
let greeting = "say Hello instead"; // error: Identifier 'greeting' has already
been declared
Click to edit Master title style
76
76
• if the same variable is defined in different scopes, there will be no error:
let greeting = "say Hi";
if (true) {
let greeting = "say Hello instead";
console.log(greeting); // "say Hello instead"
}
console.log(greeting); // "say Hi“
Why is there no error? This is because both instances are treated as different variables
since they have different scopes.
Click to edit Master title style
77
Const
77
• Variables declared with the const maintain constant values. const declarations share
some similarities with let declarations.
• const declarations are block scoped
• Like let declarations, const declarations can only be accessed within the block they
were declared.
• const cannot be updated or re-declared
• This means that the value of a variable declared with const remains the same within its
scope. It cannot be updated or re-declared. So if we declare a variable with const, we
can neither do this:
const greeting = "say Hi";
greeting = "say Hello instead";// error: Assignment to constant variable.
Nor this:
const greeting = "say Hi";
const greeting = "say Hello instead";// error: Identifier 'greeting' has already been
declared
Click to edit Master title style
78
78
• Every const declaration, therefore, must be initialized at the time of declaration.
• This behavior is somehow different when it comes to objects declared with const. While a
const object cannot be updated, the properties of this objects can be updated. Therefore, if
we declare a const object as this:
const greeting = {
message: "say Hi",
times: 4
}
while we cannot do this:
greeting = {
words: "Hello",
number: "five"
} // error: Assignment to constant variable.
Click to edit Master title style
79
79
Click to edit Master title style
80
Thank You

More Related Content

Similar to Typescript-7 (1).pptx

CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)Dilawar Khan
 
Programming fundamental 02.pptx
Programming fundamental 02.pptxProgramming fundamental 02.pptx
Programming fundamental 02.pptxZubairAli256321
 
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfL2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfMMRF2
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.pptFatimaZafar68
 
cassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfcassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfYRABHI
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programmingHarshita Yadav
 
C Programming Lecture 3 - Elements of C.pptx
C Programming Lecture 3 - Elements of C.pptxC Programming Lecture 3 - Elements of C.pptx
C Programming Lecture 3 - Elements of C.pptxMurali M
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxhardii0991
 
CSC111-Chap_02.pdf
CSC111-Chap_02.pdfCSC111-Chap_02.pdf
CSC111-Chap_02.pdf2b75fd3051
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2ndConnex
 
Python Fundamentals for the begginers in programming
Python Fundamentals for the begginers in programmingPython Fundamentals for the begginers in programming
Python Fundamentals for the begginers in programmingbsse20142018
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2Knoldus Inc.
 
Visual Basic Fundamentals
Visual Basic FundamentalsVisual Basic Fundamentals
Visual Basic FundamentalsDivyaR219113
 
Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxlemonchoos
 

Similar to Typescript-7 (1).pptx (20)

CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)
 
Programming fundamental 02.pptx
Programming fundamental 02.pptxProgramming fundamental 02.pptx
Programming fundamental 02.pptx
 
Data structure
Data structureData structure
Data structure
 
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdfL2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
L2 C# Programming Comments, Keywords, Identifiers, Variables.pdf
 
programming week 2.ppt
programming week 2.pptprogramming week 2.ppt
programming week 2.ppt
 
cassignmentii-170424105623.pdf
cassignmentii-170424105623.pdfcassignmentii-170424105623.pdf
cassignmentii-170424105623.pdf
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
C Programming Lecture 3 - Elements of C.pptx
C Programming Lecture 3 - Elements of C.pptxC Programming Lecture 3 - Elements of C.pptx
C Programming Lecture 3 - Elements of C.pptx
 
Qtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscriptQtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscript
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
lec 2.pptx
lec 2.pptxlec 2.pptx
lec 2.pptx
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptx
 
CSC111-Chap_02.pdf
CSC111-Chap_02.pdfCSC111-Chap_02.pdf
CSC111-Chap_02.pdf
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Python Fundamentals for the begginers in programming
Python Fundamentals for the begginers in programmingPython Fundamentals for the begginers in programming
Python Fundamentals for the begginers in programming
 
Data Handling
Data HandlingData Handling
Data Handling
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2
 
Visual Basic Fundamentals
Visual Basic FundamentalsVisual Basic Fundamentals
Visual Basic Fundamentals
 
Chapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptxChapter7-Introduction to Python.pptx
Chapter7-Introduction to Python.pptx
 

Recently uploaded

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 

Recently uploaded (20)

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 

Typescript-7 (1).pptx

  • 1. Click to edit Master title style 1 Typescript
  • 2. Click to edit Master title style 2 Introduction to TypeScript • TypeScript is a super set 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. • TypeScript files use the .ts extension rather than the .js extension of JavaScript files. 2
  • 3. Click to edit Master title style 3 3 • The following diagram shows the relationship between TypeScript and JavaScript:
  • 4. Click to edit Master title style 4 4 • TypeScript introduced a great deal of syntax taken from object-oriented programming, including but not limited to: • interfaces, • classes, • enumerated types, • generics, • modules. • abstract classes or access modifiers are still nowhere to be found in JavaScript, while TypeScript has them.
  • 5. Click to edit Master title style 5 Advantages 5 • TypeScript is an open-source language with continuous development and maintenance by Microsoft. • TypeScript runs on any browser or JavaScript engine. • TypeScript is similar to JavaScript and uses the same syntax and semantics. All of TypeScript's code finally gets converted into JavaScript. This allows a quicker learning curve for front-end developers currently coding in JavaScript. • TypeScript is also closer in syntax to backend languages like Java and Scala. This helps backend developers write front-end code faster.
  • 6. Click to edit Master title style 6 Basic typescript program 6 let message: string = 'Hello, World!'; console.log(message); Example 2 – function addNumbers(a: number, b: number) { return a + b; } var sum: number = addNumbers(10, 15) console.log('Sum of the two numbers is: ' +sum);
  • 7. Click to edit Master title style 7 Datatypes 7 • Number type – it is used to declare a variable that holds a number. Syntax – let price : number = 20; let price : number = 3.5; • String 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. let description = `This TypeScript string can span multiple lines`;
  • 8. Click to edit Master title style 8 8 • Boolean Types - The TypeScript boolean type allows two values: true and false. It’s one of the primitive types in TypeScript. let pending: boolean; pending = true;
  • 9. Click to edit Master title style 9 9 • Array - 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[]; • let skills = ['Problem Sovling','Software Design','Programming']; • TypeScript arrays can access the properties and methods of a JavaScript. • Example • let series = [1, 2, 3]; • console.log(series.length); // 3
  • 10. Click to edit Master title style 10 10 • Array indices and length
  • 11. Click to edit Master title style 11 Any type 11 • Sometimes, you may need to store a value in a variable. • Any type can handle any values. • To do so, you use the any type. The any type allows you to assign a value of any type to a variable: • Use the any type to store a value that you don’t actually know its type at the compile-time
  • 12. Click to edit Master title style 12 12
  • 13. Click to edit Master title style 13 Introduction to TypeScript object type 13 • The following are primitive types in TypeScript: • number • bigint • string • boolean • null • undefined The TypeScript object type represents all values that are not in primitive types.
  • 14. Click to edit Master title style 14 14 Void - Generally used on function return-types Declaring variables of type void is not useful because you can only assign null Null - It is used when an object does not have any value Undefined - Denotes value given to uninitialized variable In TypeScript, both undefined and null actually have their types named undefined and null respectively. Much like void, they’re not extremely useful on their own: By default null and undefined are subtypes of all other types. That means you can assign null and undefined to something like number.
  • 15. Click to edit Master title style 15 Enum 15 • Enums or enumerations are a new data type supported in TypeScript. • In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values. • There are three types of enums: • Numeric enum • String enum • Heterogeneous enum • Numeric ENum - Numeric enums are number-based enums i.e. they store string values as numbers. • Enums can be defined using the keyword enum.
  • 16. Click to edit Master title style 16 16 • Examle numeric enum - • enum PrintMedia { • Newspaper, • Newsletter, • Magazine, • Book • } In the above example, we have an enum named PrintMedia. The enum has four values: Newspaper, Newsletter, Magazine, and Book. Here, enum values start from zero and increment by 1 for each member. Newspaper = 0 Newsletter = 1 Magazine = 2 Book = 3 Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
  • 17. Click to edit Master title style 17 17 • We also have the option to initialize the first numeric value ourselves. For example, we can write the same enum as: • enum PrintMedia { • Newspaper = 1, • Newsletter, • Magazine, • Book • } • The first member, Newspaper, is initialized with the numeric value 1. The remaining members will be incremented by 1 from the numeric value of the first value. Thus, in the above example, Newsletter would be 2, Magazine would be 3 and Book would be 4.
  • 18. Click to edit Master title style 18 String Enum 18 • String enums are similar to numeric enums, except that the enum values are initialized with string values rather than numeric values. • The benefits of using string enums is that string enums offer better readability. enum PrintMedia { Newspaper = "NEWSPAPER", Newsletter = "NEWSLETTER", Magazine = "MAGAZINE", Book = "BOOK" } // Access String Enum PrintMedia.Newspaper; //returns NEWSPAPER PrintMedia['Magazine']; //returns MAGAZINE
  • 19. Click to edit Master title style 19 19 • In the example, we have defined a string enum, PrintMedia, with the same values as the numeric enum above, with the difference that these enum values are initialized with string literals. • The difference between numeric and string enums is that numeric enum values are auto-incremented, while string enum values need to be individually initialized.
  • 20. Click to edit Master title style 20 Heterogenous Enum 20 • Heterogeneous enums are enums that contain both string and numeric values. Example – enum Status { Active = 'ACTIVE', Deactivate = 1, Pending }
  • 21. Click to edit Master title style 21 Tuples 21 • TypeScript introduced a new data type called Tuple. Tuple can contain two values of different data types. • example of number, string and tuple type variables. var empId: number = 1; var empName: string = "Steve"; // Tuple type variable var employee: [number, string] = [1, "Steve"]; In the above example, we have defined a variable empId as number type and empName as string type with values. Here, we declared and assigned two variables to id and name of an employee. employee is the tuple type variable with two values of number and string type.
  • 22. Click to edit Master title style 22 22 • A tuple type variable can include multiple data types as shown below. • var employee: [number, string] = [1, "Steve"]; • var person: [number, string, boolean] = [1, "Steve", true]; You can declare an array of tuple also. • var employee: [number, string][]; • employee = [[1, "Steve"], [2, "Bill"], [3, "Jeff"]]; • Accessing Tuple Elements • We can access tuple elements using index, the same way as an array. An index starts from zero. • var employee: [number, string] = [1, "Steve"]; • employee[0]; // returns 1 • employee[1]; // returns "Steve"
  • 23. Click to edit Master title style 23 How to declare object 23 • 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' }; console.log(employee);
  • 24. Click to edit Master title style 24 Functions in Typescript 24 • A function definition specifies what and how a specific task would be done. • A function must be called so as to execute it. • Functions may also return value along with control, back to the caller. • Parameters are a mechanism to pass values to functions. Syntax function function_name (param1[:type], param2[:type], param3[:type])
  • 25. Click to edit Master title style 25 Named Functions 25 • A named function is one where you declare and call a function by its given name. function display() { console.log("Hello TypeScript!"); } display(); //Output: Hello TypeScript Functions can also include parameter types and return type. function Sum(x: number, y: number) : number { return x + y; } Sum(2,3); // returns 5
  • 26. Click to edit Master title style 26 Anonymous Functions 26 • An anonymous function is one which is defined as an expression. • This expression is stored in a variable. So, the function itself does not have a name. • These functions are invoked using the variable name that the function is stored in. let greeting = function() { console.log("Hello TypeScript!"); }; greeting(); //Output: Hello TypeScript! An anonymous function can also include parameter types and return type. let Sum = function(x: number, y: number) : number { return x + y; } Sum(2,3); // returns 5
  • 27. Click to edit Master title style 27 Optional Parameters 27 • Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. • Parameter can be marked optional by appending (?) question mark to its name. Example Normal function – function function_name (param1[:type], param2[:type], param3[:type]) Optional Function – function function_name (param1[:type], param2[:type], param3 ?[:type])
  • 28. Click to edit Master title style 28 Default Parameters 28 • Function parameters can also be assigned values by default. • such parameters can also be explicitly passed values Syntax – function function_name(param1[:type],param2[:type] = default_value) { } Note − A parameter cannot be declared optional and default at the same time.
  • 29. Click to edit Master title style 29 Arrow Functions 29 • Fat arrow notations are used for anonymous functions i.e for function expressions. They are also called lambda functions in other languages. Syntax – (param1, param2, ..., paramN) => expression Using fat arrow =>, we dropped the need to use the function keyword. Parameters are passed in the parenthesis (), and the function expression is enclosed within the curly brackets { }. let sum = (x: number, y: number): number => { return x + y; } sum(10, 20); //returns 30
  • 30. Click to edit Master title style 30 Rest Parameters 30 • TypeScript introduced rest parameters to accommodate n number of parameters easily. • When the number of parameters that a function will receive is not known or can vary, we can use rest parameters. • TypeScript, we can use the rest parameter denoted by ellipsis ... • We can pass zero or more arguments to the rest parameter. • function Greet(greeting: string, ...names: string[]) { • return greeting + " " + names.join(", ") + "!"; • } Greet("Hello", "Steve", "Bill"); // returns "Hello Steve, Bill!" • Greet("Hello");// returns "Hello !"
  • 31. Click to edit Master title style 31 Control Flow Statement 31 • IF …Else statement • What is 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 Syntax- if(condition) { // if-statement }
  • 32. Click to edit Master title style 32 If…else Statment 32 • 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; }
  • 33. Click to edit Master title style 33 33
  • 34. Click to edit Master title style 34 If…else if…else statment 34 • 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.
  • 35. Click to edit Master title style 35 Ternary Operator 35 • A ternary operator is denoted by '?' and is used as a short cut for an if..else statement. • It checks for a boolean condition and executes one of the two statements, depending on the result of the boolean condition. Syntax Boolean expression? First statement : second statement Example let x: number = 10, y = 20; x > y? console.log('x is greater than y.') : console.log('x is less than or equal to y.')
  • 36. Click to edit Master title style 36 36
  • 37. Click to edit Master title style 37 Switch 37 • The switch statement is used to check for multiple values and executes sets of statements for each of those values. • A switch statement has one block of code corresponding to each value and can have any number of such blocks. • When the match to a value is found, the corresponding block of code is executed.
  • 38. Click to edit Master title style 38 Switch 38
  • 39. Click to edit Master title style 39 39 Syntax – switch(expression) { case constant-expression1: { //statements; break; } case constant_expression2: { //statements; break; } default: { //statements; break; } }
  • 40. Click to edit Master title style 40 40 • The following rules are applied on the switch statement: • The switch statement can include constant or variable expression which can return a value of any data type. • There can be any number of case statements within a switch. The case can include a constant or an expression. • We must use break keyword at the end of each case block to stop the execution of the case block. • The return type of the switch expression and case expression must match. • The default block is optional.
  • 41. Click to edit Master title style 41 41 • Example – let day : number = 4; switch (day) { case 0: console.log("It is a Sunday."); break; case 1: console.log("It is a Monday."); break; case 2: console.log("It is a Tuesday."); break; default: console.log("No such day exists!"); break; }
  • 42. Click to edit Master title style 42 TypeScript - for Loops 42 • TypeScript supports the following for loops: • for loop • for..of loop • for..in loop
  • 43. Click to edit Master title style 43 For loop 43 • The for loop is used to execute a block of code a given number of times, which is specified by a condition. Syntax for (first expression; second expression; third expression ) { // statements to be executed repeatedly } the first expression is executed before the loop starts. The second expression is the condition for the loop to execute. And the third expression is executed after the execution of every code block.
  • 44. Click to edit Master title style 44 44
  • 45. Click to edit Master title style 45 For…of Loop 45 • TypeScript includes the for...of loop to iterate and access elements of an array • The for...of loop can also return a character from a string value. Example – let str = "Hello World"; for (var char of str) { console.log(char); // prints chars: H e l l o W o r l d } Example – let arr = [10, 20, 30, 40]; for (var val of arr) { console.log(val); // prints values: 10, 20, 30, 40 }
  • 46. Click to edit Master title style 46 For…in Loop 46 • Another form of the for loop is for...in. This can be used with an array. • The for...in loop iterates through a list or collection and returns an index on each iteration. Example let arr = [10, 20, 30, 40]; for (var index in arr) { console.log(index); // prints indexes: 0, 1, 2, 3 console.log(arr[index]); // prints elements: 10, 20, 30, 40 }
  • 47. Click to edit Master title style 47 Typescript While Loop 47 • The while loop is another type of loop that checks for a specified condition before beginning to execute the block of statements. • The loop runs until the condition value is met. Syntax – while (condition expression) { // code block to be executed } The condition expression checks for a specified condition before running the block of code. Example – let i: number = 2; while (i < 4) { console.log( "Block statement execution no." + i ) i++; }
  • 48. Click to edit Master title style 48 Do…while loop 48 • The do..while loop is similar to the while loop, except that the condition is given at the end of the loop. • The do..while loop runs the block of code at least once before checking for the specified condition. • For the rest of the iterations, it runs the block of code only if the specified condition is met. Syntax- do { // code block to be executed } while (condition expression);
  • 49. Click to edit Master title style 49 49 • Example – let i: number = 2; do { console.log("Block statement execution no." + i ) i++; } while ( i < 4)
  • 50. Click to edit Master title style 50 Interface 50 • Interface is a structure that defines the contract in your application. It defines the syntax for classes to follow. • Classes that are derived from an interface must follow the structure provided by their interface. • The TypeScript uses interface for type checking. This is also known as "duck typing" or "structural subtyping". • An interface is defined with the keyword interface and it can include properties and method declarations using a function
  • 51. Click to edit Master title style 51 51 Interface example interface IEmployee { empCode: number; empName: string; getSalary: (number) => number; // arrow function getManagerName(number): string; } the IEmployee interface includes two properties empCode and empName. It also includes a method declaration getSalaray using an arrow function which includes one number parameter and a number return type. The getManagerName method is declared using a normal function. This means that any object of type IEmployee must define the two properties and two methods.
  • 52. Click to edit Master title style 52 Interface as type 52 • Interface in TypeScript can be used to define a type and also to implement it in the class. • The following interface IEmployee defines a type of a variable. Example interface KeyPair { key: number; value: string; } let kv1: KeyPair = { key:1, value:"Steve" }; // OK let kv2: KeyPair = { key:1, val:"Steve" }; // Compiler Error: 'val' doesn't exist in type 'KeyPair' let kv3: KeyPair = { key:1, value:100 }; // Compiler Error:
  • 53. Click to edit Master title style 53 Interface as Function Type 53 • TypeScript interface is also used to define a type of a function. This ensures the function signature. interface KeyValueProcessor { (key: number, value: string): void; }; function addKeyValue(key:number, value:string):void { console.log('addKeyValue: key = ' + key + ', value = ' + value) } let kvp: KeyValueProcessor = addKeyValue; kvp(1, 'Bill'); //Output: addKeyValue: key = 1, value = Bill
  • 54. Click to edit Master title style 54 54 interface Person { firstName: string; lastName: string; } function getFullName(person: Person) { return `${person.firstName} ${person.lastName}`; } let john = { firstName: 'John', lastName: 'Doe' }; console.log(getFullName(john));
  • 55. Click to edit Master title style 55 55 let format: StringFormat; format = function (str: string, isUpper: boolean) { return isUpper ? str.toLocaleUpperCase() : str.toLocaleLowerCase(); }; console.log(format('hi', false)); interface StringFormat { (str: string, isUpper: boolean): string }
  • 56. Click to edit Master title style 56 Classes 56 • In object-oriented programming languages like Java and C#, classes are the fundamental entities used to create reusable components. • Functionalities are passed down to classes and objects are created from classes. • TypeScript introduced classes to avail the benefit of object-oriented techniques like encapsulation and abstraction. The class in TypeScript is compiled to plain JavaScript functions by the TypeScript compiler to work across platforms and browsers. • A class can include the following: • Constructor • Properties • Methods
  • 57. Click to edit Master title style 57 Class example 57 class Employee { empCode: number; empName: string; constructor(code: number, name: string) { this.empName = name; this.empCode = code; } getSalary() : number { return 10000; } }
  • 58. Click to edit Master title style 58 Constructor 58 • The constructor is a special type of method which is called when creating an object. In TypeScript, the constructor method is always defined with the name "constructor". Example – class Employee { empCode: number; empName: string; constructor(empcode: number, name: string ) { this.empCode = empcode; this.name = name; } }
  • 59. Click to edit Master title style 59 59 • In the example, the Employee class includes a constructor with the parameters empcode and name. In the constructor, members of the class can be accessed using this keyword e.g. this.empCode or this.name. • It is not necessary for a class to have a constructor.
  • 60. Click to edit Master title style 60 Creating object of class 60 • An object of the class can be created using the new keyword. class Employee { empCode: number; empName: string; } let emp = new Employee(); Here, we create an object called emp of type Employee using let emp = new Employee();. The above class does not include any parameterized constructor so we cannot pass values while creating an object. If the class includes a parameterized constructor, then we can pass the values while creating the object.
  • 61. Click to edit Master title style 61 Inheritance in class 61 • Just like object-oriented languages such as Java and C#, TypeScript classes can be extended to create new classes with inheritance, using the keyword extends. • The key to understanding Inheritance is that it provides code re-usability. In place of writing the same code, again and again, we can simply inherit the properties of one class into the other. • along with the inherited properties and methods, a child class can have its own properties and methods. • We must call super() method first before assigning values to properties in the constructor of the derived class.
  • 62. Click to edit Master title style 62 62 class Person { name: string; constructor(name: string) { this.name = name; } } class Employee extends Person { empCode: number; constructor(empcode: number, name:string) { super(name); this.empCode = empcode; } displayName():void { console.log("Name = " + this.name + ", Employee Code = " + this.empCode); } } let emp = new Employee(100, "Bill"); emp.displayName();
  • 63. Click to edit Master title style 63 Class implements interface 63 • A class can implement single or multiple interfaces. interface IPerson { name: string; display():void; } interface IEmployee { empCode: number; } class Employee implements IPerson, IEmployee { empCode: number; name: string; constructor(empcode: number, name:string) { this.empCode = empcode; this.name = name; }
  • 64. Click to edit Master title style 64 64 display(): void { console.log("Name = " + this.name + ", Employee Code = " + this.empCode); } } let per:IPerson = new Employee(100, "Bill"); per.display(); // Name = Bill, Employee Code = 100 let emp:IEmployee = new Employee(100, "Bill"); emp.display(); //Compiler Error: Property 'display' does not exist on type 'IEmployee'
  • 65. Click to edit Master title style 65 Method Overriding 65 • When a child class defines its own implementation of a method from the parent class, it is called method overriding. • the children classes have a method of the same name as that of the parent class.
  • 66. Click to edit Master title style 66 TypeScript - Data Modifiers 66 • In object-oriented programming, the concept of 'Encapsulation' is used to make class members public or private i.e. a class can control the visibility of its data members. This is done using access modifiers. • There are three types of access modifiers in TypeScript: public, private and protected. • Public • Private • Protected
  • 67. Click to edit Master title style 67 Public – Data modifiers 67 • By default, all members of a class in TypeScript are public. All the public members can be accessed anywhere without any restrictions. Example – class Employee { public empCode: string; empName: string; } let emp = new Employee(); emp.empCode = 123; emp.empName = "Swati"; In the above example, empCode and empName are declared as public. So, they can be accessible outside of the class using an object of the class. notice that there is not any modifier applied before empName, as TypeScript treats properties and methods as public by default if no modifier is applied to them.
  • 68. Click to edit Master title style 68 Private Data modifiers 68 • The private access modifier ensures that class members are visible only to that class and are not accessible outside the containing class. class Employee { private empCode: number; empName: string; } let emp = new Employee(); emp.empCode = 123; // Compiler Error emp.empName = "Swati";//OK In the above example, we have marked the member empCode as private. Hence, when we create an object emp and try to access the emp.empCode member, it will give an error.
  • 69. Click to edit Master title style 69 Protected 69 • The protected access modifier is similar to the private access modifier, except that protected members can be accessed using their deriving classes. •
  • 70. Click to edit Master title style 70 Typescript – Read Only 70 • TypeScript includes the readonly keyword that makes a property as read-only in the class or interface. • Prefix readonly is used to make a property as read-only. Read-only members can be accessed outside the class, but their value cannot be changed. • Since read-only members cannot be changed outside the class, they either need to be initialized at declaration or initialized inside the class constructor.
  • 71. Click to edit Master title style 71 71 • Example – class Employee { readonly empCode: number; empName: string; constructor(code: number, name: string) { this.empCode = code; this.empName = name; } } let emp = new Employee(10, "John"); emp.empCode = 20; //Compiler Error emp.empName = 'Bill'; In the above example, we have the Employee class with two properties- empName and empCode. Since empCode is read only, it can be initialized at the time of declaration or in the constructor. If we try to change the value of empCode after the object has been initialized, the compiler shows the following compilation error:
  • 72. Click to edit Master title style 72 Var , Let and Const 72 • Scope essentially means where these variables are available for use. var declarations are globally scoped or function/locally scoped. • The scope is global when a var variable is declared outside a function. This means that any variable that is declared with var outside a function block is available for use in the whole window. • var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function. Example – var tester = "hey hi"; function newFunction() { var hello = "hello"; } console.log(hello); // error: hello is not defined
  • 73. Click to edit Master title style 73 73 • Var Variables can be re-declared and updated Example – var greeter = "hey hi"; var greeter = "say Hello instead";
  • 74. Click to edit Master title style 74 Let 74 • A block is a chunk of code bounded by {}. A block lives in curly braces. Anything within curly braces is a block. • So a variable declared in a block with let is only available for use within that block. let greeting = "say Hi"; let times = 4; if (times > 3) { let hello = "say Hello instead"; console.log(hello);// "say Hello instead" } console.log(hello) // hello is not defined
  • 75. Click to edit Master title style 75 75 • let can be updated but not re-declared. • Just like var, a variable declared with let can be updated within its scope. Unlike var, a let variable cannot be re-declared within its scope. So while this will work: let greeting = "say Hi"; greeting = "say Hello instead"; This will return an error – let greeting = "say Hi"; let greeting = "say Hello instead"; // error: Identifier 'greeting' has already been declared
  • 76. Click to edit Master title style 76 76 • if the same variable is defined in different scopes, there will be no error: let greeting = "say Hi"; if (true) { let greeting = "say Hello instead"; console.log(greeting); // "say Hello instead" } console.log(greeting); // "say Hi“ Why is there no error? This is because both instances are treated as different variables since they have different scopes.
  • 77. Click to edit Master title style 77 Const 77 • Variables declared with the const maintain constant values. const declarations share some similarities with let declarations. • const declarations are block scoped • Like let declarations, const declarations can only be accessed within the block they were declared. • const cannot be updated or re-declared • This means that the value of a variable declared with const remains the same within its scope. It cannot be updated or re-declared. So if we declare a variable with const, we can neither do this: const greeting = "say Hi"; greeting = "say Hello instead";// error: Assignment to constant variable. Nor this: const greeting = "say Hi"; const greeting = "say Hello instead";// error: Identifier 'greeting' has already been declared
  • 78. Click to edit Master title style 78 78 • Every const declaration, therefore, must be initialized at the time of declaration. • This behavior is somehow different when it comes to objects declared with const. While a const object cannot be updated, the properties of this objects can be updated. Therefore, if we declare a const object as this: const greeting = { message: "say Hi", times: 4 } while we cannot do this: greeting = { words: "Hello", number: "five" } // error: Assignment to constant variable.
  • 79. Click to edit Master title style 79 79
  • 80. Click to edit Master title style 80 Thank You