0% found this document useful (0 votes)
572 views75 pages

Type Script

The document provides a comprehensive overview of TypeScript, an open-source, object-oriented programming language that extends JavaScript with static typing. It covers topics such as TypeScript's internal architecture, environment setup, types, functions, classes, and advantages over JavaScript. Additionally, it explains how to write and compile TypeScript code, highlighting its features and components like the TypeScript compiler and language services.

Uploaded by

havahix348
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)
572 views75 pages

Type Script

The document provides a comprehensive overview of TypeScript, an open-source, object-oriented programming language that extends JavaScript with static typing. It covers topics such as TypeScript's internal architecture, environment setup, types, functions, classes, and advantages over JavaScript. Additionally, it explains how to write and compile TypeScript code, highlighting its features and components like the TypeScript compiler and language services.

Uploaded by

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

TypeScript

By- Ms. Sonu Kumavat


Assistant Professor
Topics
➢ Introduction
➢ TypeScript Internal Architecture
➢ TypeScript Environment Setup
➢ TypeScript Types
➢ Variables and Operators
➢ Decision Making and loops
➢ TypeScript Functions
➢ TypeScript Classes and Objects
➢ TypeScript Modules
Introduction
● Open-source
● Object-oriented language developed
● Extends JavaScript
● Typed superset of JavaScript that compiles to plain JavaScript.
Why TypeScript?
● JavaScript is a dynamic programming language with no type system.
● JS Provides primitive types like string, number, object, etc., but it doesn't check
assigned values.
● variables are declared using the var keyword, and it can point to any value.
● It doesn't support classes and other object-oriented features.
● Errors can be caught at compile time rather than at runtime.
Why TypeScript?
● TypeScript compiles into simple JavaScript.
● The TypeScript compiler is also implemented in TypeScript and can be used with
any browser or JavaScript engines like Node.js.
● TypeScript needs an ECMAScript 3 or higher compatible environment to
compile.
● Frameworks like Angular.js and WinJS are written in TypeScript.
How to use TypeScript?
● TypeScript code is written in a file with its extension (.ts) and then compiled
into JavaScript using the TypeScript compiler.
● A TypeScript file can be written in any code editor.
● A TypeScript compiler needs to be installed on your platform.
● Once installed, the command tsc<filename>.ts compiles the TypeScript code
into a plain JavaScript file.
● JavaScript files can then be included in the HTML and run on any browser.
How to use TypeScript?
● Install node.js package manager
● Verify installation: node -v
● TypeScript installation: npm install -g typescript
● Write a code in text editor: Notepad
● Save file: (file_name.ts)
● Run typescript file: tsc file_name.ts
● Run the javascript file: node file_name.js
TypeScript Program
● To print simple message:
console.log(“Hello World!”);
Or
var message: string = “Hello World!”;
console.log(message);
TypeScript Features
● Cross-Platform
● Object-oriented Language
● Static type-checking
● Optional Static Typing
● DOM manipulation
● ES 6 features
TypeScript Advantages
● TypeScript is an open-source language.
● Runs on any browser or JavaScript engine.
● It 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.
● TypeScript code can be called from an existing JavaScript code. It also works
with existing JavaScript frameworks and libraries without any issues.
TypeScript Advantages
● TypeScript code can be called from an existing JavaScript code. It also works
with existing JavaScript frameworks and libraries without any issues.
● The TypeScript Definition file, with .d.ts extension, provides support for
existing JavaScript libraries like JQuery, D3.js, etc.
● It has support for the latest JavaScript features from ECMAScript 2015. It
includes features from ES6 and ES7 that can run in ES5-level JavaScript
engines like Node.js.
JavaScript TypeScript

It doesn't support strongly typed or static typing. It supports strongly typed or static typing feature.

Netscape developed it in 1995. Anders Hejlsberg developed it in 2012.

JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.

It is directly run on the browser. It is not directly run on the browser.

It is just a scripting language. It supports object-oriented programming concept like


classes, interfaces, inheritance, generics, etc.

It doesn't support optional parameters. It supports optional parameters.

It is interpreted language that's why it highlighted the It compiles the code and highlighted errors during the
errors at runtime. development time.

JavaScript doesn't support modules. TypeScript gives support for modules.

In this, number, string are the objects. In this, number, string are the interface.
JavaScript TypeScript

It doesn't support strongly typed or static typing. It supports strongly typed or static typing feature.

Example: Example:

<script> function addNumbers(a, b) {

function addNumbers(a, b) { return a + b;

return a + b; }

} var sum = addNumbers(15, 25);

var sum = addNumbers(15, 25); console.log('Sum of the numbers is: ' + sum);

document.write('Sum of the numbers is: ' + sum);

</script>
TypeScript Internal Architecture
Components of TypeScript
● The TypeScript language is internally divided into three main layers.
● Each of these layers is divided into sublayers or components. In the diagram, we
can see the three layers and each of their internal components. These layers are:
1. Language
2. The TypeScript Compiler
3. The TypeScript Language Services

1. Language
It features the TypeScript language elements. It comprises elements like syntax,
keywords, and type annotations.
Components of TypeScript
2. The TypeScript Compiler
● The TypeScript compiler (TSC) transform the TypeScript program equivalent to its
JavaScript code. It also performs the parsing, and type checking of our TypeScript code to
JavaScript code.

● Browser doesn't support the execution of TypeScript code directly. So the program written
in TypeScript must be re-written in JavaScript equivalent code which supports the
execution of code in the browser directly. To perform this, TypeScript comes with
TypeScript compiler named "tsc." The current version of TypeScript compiler supports
ES6, by default. It compiles the source code in any module like ES6, SystemJS, AMD, etc.
Components of TypeScript
We can install the TypeScript compiler by locally, globally, or both with any npm package. Once
installation completes, we can compile the TypeScript file by running "tsc" command on the command
line.

Compiler Configuration
The TypeScript compiler configuration is given in tsconfig.json file

Declaration file
When we compile the TypeScript source code, it gives an option to generate a declaration file with the
extension .d.ts. This file works as an interface to the components in the compiled JavaScript. If a file
has an extension .d.ts, then each root level definition must have the declare keyword prefixed to it. It
makes clear that there will be no code emitted by TypeScript, which ensures that the declared item
will exist at runtime. The declaration file provides IntelliSense for JavaScript libraries like jQuery.
Components of TypeScript

3. The TypeScript Language Services


The language service provides information which helps editors and other tools to
give better assistance features such as automated refactoring and IntelliSense. It
exposes an additional layer around the core-compiler pipeline. It supports some
standard typical editor operations like code formatting and outlining, colorization,
statement completion, signature help, etc.
The TypeScript compiler is responsible for converting TypeScript code to JavaScript. It is
written in TypeScript and runs on Node.js. The compiler is divided into three main parts −

1. The Scanner − The scanner reads the source code and produces a stream of tokens. A
token is a sequence of characters that represents a single element in the code, such as
a keyword, variable name, or operator.
2. The Parser − The parser takes the stream of tokens produced by the scanner and
creates an abstract syntax tree (AST). The AST is a representation of the source code
that is easier for the compiler to analyze.
3. The Checker − The checker analyzes the AST and performs type checking. It checks
that variables are used correctly and that function arguments match their expected
types.
TypeScript Type
1. The TypeScript language supports different types of values.
2. It provides data types for the JavaScript to transform it into a strongly typed
programming language.
3. JavaScript doesn't support data types, but with the help of TypeScript, we can use
the data types feature in JavaScript.
4. TypeScript plays an important role when the object-oriented programmer wants
to use the type feature in any scripting language or object-oriented programming
language.
5. The Type System checks the validity of the given values before the program uses
them. It ensures that the code behaves as expected.
TypeScript Type
● TypeScript provides data types as an optional Type System. We can classify
the TypeScript data type as following.
Built-in or Primitive Type
● The TypeScript has five built-in data types
Number
● Like JavaScript, all the numbers in TypeScript are stored as floating-point values.
● These numeric values are treated like a number data type.
● The numeric data type can be used to represents both integers and fractions.
● TypeScript also supports Binary(Base 2), Octal(Base 8), Decimal(Base 10), and
Hexadecimal(Base 16) literals.

Syntax:

let identifier: number = value;


Number
Examples:-

let first: number = 12.0; // number


let second: number = 0x37CF; // hexadecimal
let third: number = 0o377 ; // octal
let fourth: number = 0b111001; // binary

console.log(first); // 123
console.log(second); // 14287
console.log(third); // 255
console.log(fourth); // 57
String
● We will use the string data type to represents the text in TypeScript.
● String type work with textual data.
● We include string literals in our scripts by enclosing them in single or double
quotation marks.
● It also represents a sequence of Unicode characters.
● It embedded the expressions in the form of $ {expr}.

Syntax

let identifier: string = " ";

Or
let identifier: string = ' ';
String
Examples

let empName: string = "Rohan";


let empDept: string = "IT";
// Before-ES6
let output1: string = employeeName + " works in the " + employeeDept + "
department.";
// After-ES6
let output2: string = `${empName} works in the ${empDept} department.`;

console.log(output1);//Rohan works in the IT department.


console.log(output2);//Rohan works in the IT department.
Boolean
The string and numeric data types can have an unlimited number of different values,
whereas the Boolean data type can have only two values. They are "true" and "false." A
Boolean value is a truth value which specifies whether the condition is true or not.

Syntax

let identifier: BooleanBoolean = Boolean value;


Examples

let isDone: boolean = false;


Void
A void is a return type of the functions which do not return any type of value. It is used
where no data type is available. A variable of type void is not useful because we can only
assign undefined or null to them. An undefined data type denotes uninitialized variable,
whereas null represents a variable whose value is undefined.
Syntax
let unusable: void = undefined;
Examples
1. function helloUser(): void {
alert("This is a welcome message");
}
2. let tempNum: void = undefined;
tempNum = null;
tempNum = 123; //Error
Null
Null represents a variable whose value is undefined. Much like the void, it is not extremely
useful on its own. The Null accepts the only one value, which is null. The Null keyword is
used to define the Null type in TypeScript, but it is not useful because we can only assign a
null value to it.

Examples

let num: number = null;


let bool: boolean = null;
let str: string = null;
User-Defined DataType
Array
An array is a collection of elements of the same data type. Like JavaScript, TypeScript also
allows us to work with arrays of values. An array can be written in two ways:

1. Use the type of the elements followed by [] to denote an array of that element type:

var list : number[] = [1, 3, 5];


2. The second way uses a generic array type:

var list : Array<number> = [1, 3, 5];


Tuple

The Tuple is a data type which includes two sets of values of different data types. It allows
us to express an array where the type of a fixed number of elements is known, but they are
not the same. For example, if we want to represent a value as a pair of a number and a
string, then it can be written as:

// Declare a tuple
let a: [string, number];

// Initialize it
a = ["hi", 8, "how", 5]; // OK
Interface
An Interface is a structure which acts as a contract in our application. It defines the syntax
for classes to follow, means a class which implements an interface is bound to implement
all its members. It cannot be instantiated but can be referenced by the class which
implements it. The TypeScript compiler uses interface for type-checking that is also known
as "duck typing" or "structural subtyping."

interface Calc {
subtract (first: number, second: number): any;
}

let Calculator: Calc = {


subtract(first: number, second: number) {
return first - second;
}
}
Class
Classes are used to create reusable components and acts as a template for creating objects.
It is a logical entity which store variables and functions to perform operations. TypeScript
gets support for classes from ES6. It is different from the interface which has an
implementation inside it, whereas an interface does not have any implementation inside it.
class Student
{
RollNo: number;
Name: string;
constructor(_RollNo: number, Name: string)
{
this.RollNo = _rollNo;
this.Name = _name;
}
showDetails()
{
console.log(this.rollNo + " : " + this.name);
}
}
Enums
Enums define a set of named constant. TypeScript provides both string-based and
numeric-based enums. By default, enums begin numbering their elements starting from 0,
but we can also change this by manually setting the value to one of its elements.
TypeScript gets support for enums from ES6.

Example

enum Color {
Red, Green, Blue
};
let c: Color;
ColorColor = Color.Green;
Functions
A function is the logical blocks of code to organize the program. Like JavaScript,
TypeScript can also be used to create functions either as a named function or as an
anonymous function. Functions ensure that our program is readable, maintainable, and
reusable. A function declaration has a function's name, return type, and parameters.

Example

//named function with number as parameters type and return type


function add(a: number, b: number): number {
return a + b;
}

//anonymous function with number as parameters type and return type


let sum = function (a: number, y: number): number {
return a + b;
TypeScript Variables
● A variable is the storage location, which is used to store value/information to be referenced and
used by programs.
● It acts as a container for value in code and must be declared before the use. We can declare a
variable by using the var keyword.
● In TypeScript, the variable follows the same naming rule as of JavaScript variable declaration.
● These rules are-
○ The variable name must be an alphabet or numeric digits.
○ The variable name cannot start with digits.
○ The variable name cannot contain spaces and special character, except the underscore(_)
and the dollar($) sign.
TypeScript Variables
● In ES6, we can define variables using let and const keyword. These variables have
similar syntax for variable declaration and initialization but differ in scope and usage.
● In TypeScript, there is always recommended to define a variable using let keyword
because it provides the type safety.
● The let keyword is similar to var keyword in some respects, and const is an let which
prevents prevents re-assignment to a variable.
Variable Declaration
We can declare a variable in one of the four ways:

1. Declare type and value in a single statement

var [identifier] : [type-annotation] = value;


2. Declare type without value. Then the variable will be set to undefined.

var [identifier] : [type-annotation];


3. Declare its value without type. Then the variable will be set to any.

var [identifier] = value;


4. Declare without value and type. Then the variable will be set to any and initialized with undefined.

var [identifier];
var keyword
Generally, var keyword is used to declare a We can also access a variable of one function
variable in JavaScript. with the other function:
var x = 50; function a() {
We can also declare a variable inside the var x = 50;
function: return function b() {
function a() { var y = x+5;
var msg = " Welcome to JavaTpoint !! return y;
"; }
return msg; }
} var b = a();
a(); b(); //returns '55'
Scoping rules
● For other language programmers, they are function f()
getting some odd scoping rules for var {
declaration in JavaScript. var X = 5; //Available globally inside f()
if(true)
● Variables declared in TypeScript with the {
var keyword have function scope. var Y = 10; //Available globally inside f() console.log(X);
● This variable has global scope in the //Output 5
function where they are declared. console.log(Y); //Output 10
● It can also be accessed by any function }
which shares the same scope. console.log(X); //Output 5
console.log(Y); //Output 10
}
f();
console.log(X); //Returns undefined because value cannot
accesses from outside function
console.log(Y); //Returns undefined because value cannot
accesses from outside function
let declarations
● The let keyword is similar to the var keyword.
● The var declaration has some problems in solving programs, so ES6 introduced let keyword to
declare a variable in TypeSript and JavaScript.
● The let keyword has some restriction in scoping in comparison of the var keyword.
● The let keyword can enhance our code readability and decreases the chance of programming
error.
● The let statement are written as same syntax as the var statement:
var declaration: var b = 50;
let declaration: let b = 50;
The key difference between var and let is not in the syntax, but it differs in the semantics. The
Variable declared with the let keyword are scoped to the nearest enclosing block which can be smaller
than a function block.
Block Scoping
● When the variable declared using the let keyword, it uses block scoping or lexical scoping.
● Unlike variable declared using var keyword whose scopes leak out to their containing
function, a block-scoped variable cannot visible outside of its containing block.
function f(input: boolean) {
let x = 100;
if (input) {
// "x" exists here
let y = x + 1;
return y;
}
// Error: "y" doesn't exist here
return y;
}
● Here, we have two local variables x and y. Scope of x is limited to the body of the function
f() while the scope of y is limited to the containing if statement's block.
var let

The var keyword was introduced with The let keyword was added in ES6 (ES 2015) version of
JavaScript. JavaScript.

It has global scope. It is limited to block scope.

It can be declared globally and can be accessed It can be declared globally but cannot be accessed globally.
globally.

Variable declared with var keyword can be Variable declared with let keyword can be updated but not
re-declared and updated in the same scope. re-declared. Example:
Example: function varGreeter(){
function varGreeter(){ let a = 10;
var a = 10; let a = 20; //SyntaxError:
var a = 20; //a is replaced //Identifier 'a' has already been declared
console.log(a); console.log(a);
} }
varGreeter(); varGreeter();
var let
It is hoisted. It is not hoisted.
Example: Example:
{ {
console.log(c); // undefined. console.log(b); // ReferenceError:
//Due to hoisting //b is not defined
var c = 2; let b = 3;
} }
Operators in TypeScript
In TypeScript, an operator can be classified into the following ways.

1. Arithmetic operators
2. Comparison (Relational) operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Ternary/conditional operator
7. Concatenation operator
8. Type Operator
Decision Making
There are various types of Decision making in TypeScript:
● if statement
● if-else statement
● if-else-if ladder
● nested if statement
● switch statement
Loops in TypeScript
● When a block of code needs to be executed several number of times.
● Statements are executed sequentially: the first statement in a function is
executed first, followed by the second, and so on.
● A loop statement allows us to execute a statement or group of statements
multiple times.
● Classification of loops:
a. Definite Loop
b. Indefinite Loop
● Definite Loop
○ for loop
● Indefinite Loop
○ while
○ do… while
● break statement
● continue statement
● infinite loop
TypeScript Functions

● Functions are the fundamental building block of any applications in


JavaScript.
● It makes the code readable, maintainable, and reusable. We can use it to build
up layers of abstraction, mimicking classes, information hiding, and modules.
● In TypeScript, however, we have the concept of classes, namespaces, and
modules, but functions still are an integral part in describing how to do
things.
● TypeScript also allows adding new capabilities to the standard JavaScript
functions to make the code easier to work.
Advantage of functions
These are the main advantages of functions:

1. Code reusability: We can call a function several times without writing the same
block of code again. The code reusability saves time and reduces the program size.
2. Less coding: Functions makes our program compact. So, we don't need to write
many lines of code each time to perform a common task.
3. Easy to debug: It makes the programmer easy to locate and isolate faulty
information.
Function Aspects
1. Function declaration
2. Function definition
3. Function call

Function Creation
We can create a function in two ways. These are:
1. Named functions: When we declare and call a function by its given name, then this type of
function is known as a named function.
2. Anonymous functions: A function without a name is known as an anonymous function.
These type of functions are dynamically declared at runtime.
Function Parameter
● Parameters are the values or arguments that passed to a function.
● Compiler accepts the same number and type of arguments as defined in the
function signature.
● Function parameter can be categories into the following:
a. Optional Parameter
b. Default Parameter
c. Rest Parameter
Optional parameter
➔ In JavaScript, you can call a function without passing any arguments even though the
function specifies parameters. Therefore, JavaScript supports the optional parameters
by default.
➔ In TypeScript, the compiler checks every function call and issues an error in the
following cases:
◆ The number of arguments is different from the number of parameters specified in the
function.
◆ Or the types of arguments are not compatible with the types of function parameters.
➔ To make a function parameter optional, you use the ? after the parameter name.
Optional parameter
function multiply(a: number, b: number, c?: number): number
{
if (typeof c !== 'undefined') {
return a * b * c;
}
return a * b;
}
● Use the parameter?: type syntax to make a parameter optional.
● Use the expression typeof(parameter) !== 'undefined' to check if the parameter has
been initialized.
Default parameter
● It provides an option to set default values to the function parameters.
● If user does not pass a value to an argument, TypeScript initializes the default value
for the parameter.
function applyDiscount(price, discount = 0.05) {
return price * (1 - discount);
}
console.log(applyDiscount(100)); // 95
● The applyDiscount() function has the discount parameter as a default parameter.
● When you don’t pass the discount argument into the applyDiscount() function, the
function uses a default value which is 0.05
Typescript Arrow Function (Lambda Function)
● ES6 version of TypeScript provides an arrow function which is the shorthand syntax
for defining the anonymous function, i.e., for function expressions.
● It omits the function keyword.
● We can call it fat arrow (because -> is a thin arrow and => is a "fat" arrow).
● It is also called a Lambda function.
● The arrow function has lexical scoping of "this" keyword.
● The motivation for arrow function is:
○ When we don't need to keep typing function.
○ It lexically captures the meaning of this keyword.
○ It lexically captures the meaning of arguments.
➔ Arrow function with parameter:
let sum = (a: number, b: number): number => {
return a + b;
}
console.log(sum(20, 30)); //returns 50
◆ sum is an arrow function,
◆ "a: number, b: number" is a parameter type,
◆ ": number" is the return type,
◆ the arrow notation => separates the function parameter and the function body.
❖ Arrow function without a parameter:
let Print = () => console.log("Hello JavaTpoint!");
Print();

➢ if the function body consists of only one statement, then there is no need of the curly brackets and the
return keyword.
➢ ": number" is the return type,
➢ the arrow notation => separates the function parameter and the function body.
❖ Arrow function without a parameter: We can include the arrow function as a
property in a class.
class Student {
studCode: number;
studName: string;
constructor(code: number, name: string) {
this.studName = name;
this.studCode = code;
}
showDetail = () => console.log("Student Code: " + this.studCode + '\nStudent
Name: ' + this.studName)
}
let stud = new Student(101, 'Abhishek Mishra');
stud.showDetail();
Typescript function overloading

● Function overloading is a mechanism or ability to create multiple methods


with the same name but different parameter types and return type.
● However, it can have the same number of parameters.
● Function overloading is also known as method overloading.
● The Function/Method overloading is allowed when:
○ The function name is the same
○ The number of parameters is different in each overloaded function.
○ The number of parameters is the same, and their type is different.
○ The all overloads function must have the same return type.
● Multiplication of numbers.
Advantage of function overloading

● It saves the memory space so that program execution becomes fast.


● It provides code reusability, which saves time and efforts.
● It increases the readability of the program.
● Code maintenance is easy.
Example of function overloading

//Function with string type parameter


function add(a:string, b:string): string;
//Function with number type parameter
function add(a:number, b:number): number;
//Function Definition
function add(a: any, b:any): any {
return a + b;
}
console.log("Addition: " +add("WEB ", "X.0"));
console.log("Addition: "+add(30, 20));
Function overloading in a class
class A
{
public foo(s: string): number;
public foo(n: number): string;
public foo(arg: any): any
{
if (typeof(arg) === 'number')
return arg.toString();
if (typeof(arg) === 'string')
return arg.length;
}
}
let obj = new A();
console.log("Result: " +obj.foo(101));
console.log("Length of String: " +obj.foo("JavaTpoint"));
Function overloading in a class
A class definition can contain the following properties:

1. Fields: It is a variable declared in a class.


2. Methods: It represents an action for the object.
3. Constructors: It is responsible for initializing the object in memory.
4. Nested class and interface: It means a class can contain another class.
Object Initialization

● Object initialization means storing of data into the object.


● There are three ways to initialize an object.
a. By reference variable
b. By method
c. By Constructor
By reference variable

//Creating an object or instance


let obj = new Student();

//Initializing an object by reference variable


obj.id = 101;
obj.name = "Virat Kohli";
By constructor
● A constructor is used to initialize an object.
● In TypeScript, the constructor method is always defined with the name "constructor."
● In the constructor, we can access the member of a class by using this keyword.
//defining constructor
constructor(id: number, name:string) {
this.id = id;
this.name = name;
}
Data Hiding
● It is a technique which is used to hide the internal object details.
● A class can control the visibility of its data members from the members of the other
classes.
● This capability is termed as encapsulation or data-hiding.
● OOPs uses the concept of access modifier to implement the encapsulation.
● The access modifier defines the visibility of class data member outside its defining
class.
● TypeScript supports the three types of access modifier.
TypeScript Inheritance
● Inheritance is an aspect of OOPs languages, which provides the ability of a program
to create a new class from an existing class.
● It is a mechanism which acquires the properties and behaviors of a class from
another class.
● The class whose members are inherited is called the base class, and the class that
inherits those members is called the derived/child/subclass.
● In child class, we can override or modify the behaviors of its parent class.
● Before ES6, JavaScript uses functions and prototype-based inheritance, but
TypeScript supports the class-based inheritance which comes from ES6 version.
● The TypeScript uses class inheritance through the extends keyword.
● TypeScript supports only single inheritance and multilevel inheritance.
● It doesn't support multiple and hybrid inheritance.
TypeScript Inheritance
● Syntax:
class sub_class_name extends super_class_name
{
// methods and fields
}
● Why use inheritance?
○ We can use it for Method Overriding (so runtime polymorphism can be achieved).
○ We can use it for Code Reusability.
Inheritance Example
class Car {
Color:string
constructor(color:string) {
this.Color = color
}
}
class Audi extends Car {
Price: number
constructor(color: string, price: number) {
super(color); //super keyword is used to call the parent constructor and its values.
this.Price = price;
}
display():void {
console.log("Color of Audi car: " + this.Color);
console.log("Price of Audi car: " + this.Price);
}
}
let obj = new Audi(" Black", 8500000 );
obj.display();
Single Inheritance
● Single inheritance can inherit properties and behavior from at most one parent class.
● It allows a derived/subclass to inherit the properties and behavior of a base class that
enable the code reusability as well as we can add new features to the existing code.
● The single inheritance makes the code less repetitive.
class Shape {
Area:number
constructor(area:number) {
this.Area = area
}
}
class Circle extends Shape {
display():void {
console.log("Area of the circle: "+this.Area)
}
}
var obj = new Circle(320);
obj.display()
Multilevel Inheritance
● When a derived class is derived from another derived class, then this type of inheritance is
known as multilevel inheritance.
● Thus, a multilevel inheritance has more than one parent class.
● It is similar to the relation between Grandfather, Father, and Child.
class Animal {
eat():void {
console.log("Eating")
} }
class Dog extends Animal {
bark():void {
console.log("Barking")
} }
class BabyDog extends Dog{
weep():void {
console.log("Weeping")
} }
let obj = new BabyDog();
obj.eat();
obj.bark();
obj.weep()

You might also like