Type Script
Type Script
It doesn't support strongly typed or static typing. It supports strongly typed or static typing feature.
JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.
It is interpreted language that's why it highlighted the It compiles the code and highlighted errors during the
errors at runtime. development time.
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:
return a + b; }
var sum = addNumbers(15, 25); console.log('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
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:
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
Or
let identifier: string = ' ';
String
Examples
Syntax
Examples
1. Use the type of the elements followed by [] to denote an array of that element type:
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;
}
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
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 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
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