0% found this document useful (0 votes)
7K views

Typescript Tutorial

Typescript is a superset of JavaScript that adds types and classes. It brings support for types and class-based object-oriented programming to JavaScript. Typescript code is compiled to JavaScript. Typescript adds type safety and helps catch errors. Typescript supports primitive types like numbers and strings as well as object types. Variables, functions, and return types can be annotated with types in Typescript.

Uploaded by

bhumism303
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views

Typescript Tutorial

Typescript is a superset of JavaScript that adds types and classes. It brings support for types and class-based object-oriented programming to JavaScript. Typescript code is compiled to JavaScript. Typescript adds type safety and helps catch errors. Typescript supports primitive types like numbers and strings as well as object types. Variables, functions, and return types can be annotated with types in Typescript.

Uploaded by

bhumism303
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Typescript

https://www.tektutorialshub.com/typescript/
# What is Typescript?
-Typescript is nothing but a superset of JavaScript. It is built on top of javascript and introduces
syntax enhancements. It brings support for types and class-based object-oriented programming
paradigm to the world of Javascript. When compiled (or transpiled) it produces Javascript.
-Typescript is open source and free to use. It is designed, developed and maintained by
Microsoft.
-TypeScript provides the static type system which provides great help in catching programming
errors at compile time.
# Hello world program
let message:string = "Hello World"
console.log(message)
-The message is a variable of type string. A variable is a storage for the data. “message” is the
name of the variable. In the code above, it stores the value “Hello World”, which is a string. We
use let(or var) to create variables in typescript.
# Typescript syntax
-Typescript Syntax and basic rules that need to be followed while writing code in TypeScript.
-TypeScript is case sensitive. This means that foo is not the same as Foo.
• Typescript Statements
-A Typescript statement is an instruction to perform a specific action. A Typical Typescript
program consists of several such sequences of statements and they control the flow of the
program.
Here is an example of three statements
//statement 1 create a variable
var message;
//statement 2 assigns “Hello World” to message variable
message=”hello world”;
//statmenent 3 print out console log
console.log(message);
- ; the semicolon is used to indicate the end of a statement.
• TypeScript Expressions
-Expressions are units of code that produces value. They can appear anywhere in the code. They
can be part of the function arguments or right side of an assignment, etc
Example of Expressions
5+7 //This is an arithmetic expression that evaluates to 12
I++ //Arithmetic expression
'Something' //Primary Expressions
a && b
-The expressions can be of various types Arithmetic, String, Primary, Array & object
Initialisation, Logical, Left-Hand side. Property access, object Creation, Function definition,
invocation, etc.
• Comments in TypeScript
The Comments can be applied to the line of code or to a block of code.
-Single-line comments ( // ) − Any text between a // and the end of a line is treated as a
comment.
-Multi-line comments (/* */) − These comments may span multiple lines.
# Data Types
-The Type or the Data Type is an attribute of data that tells us what kind of value the data has.
-JavaScript has eight data types. Seven primitive types and one object Data type. The primitive
types are number, string, boolean, bigint, symbol, undefined, and null. Everything else is an
object in JavaScript.
-The TypeScript Type System supports all of them and also brings its own special types. They are
unknown, any, void & never.TypeScript also provides both numeric and string-based enums.
Enums allow a developer to define a set of named constants.

#Opting out of Type Checking


• Any
-Typescript allows us to opt-out of type checking by assigning any type to a variable. The
compiler will not perform type checking on variables whose type is any.
-any is a special data type that can hold any data. You can change the data type. We use this when
we do not know the type of data. any is specific to typescript. When a variable’s type is not given
and typescript cannot infer its type from the initialization then it will be treated as an any type.
let notSure: any = 4; //defined as any
notSure = "maybe a string instead";
notSure = false;
let stillNotSure //No Type specified. inferred as any
stillNotSure=5
stillNotSure="may be a strng instead"
stillNotSure=false;
#TypeScript Special Types
Apart from any type, typescript has three other special types. They are never, void & unknown
types.
• Never
-The never type represents the value that will never happen. We use it as the return type of a
function, which does not return a value. For example, the function that always throws an
exception is shown below.
e.g. function doSomething(): never {
throw new Error("Error has occurred");
}
• Void
-Void represents the absence of any return value. For example, the following function prints
“hello” and returns without returning a value. Hence the return type is void. It is different from
never. never means it never returns a value.
-e.g. function sayHello(): void {
console.log('Hello!')
}
• Unknown Type
-unknown type means that the type of variable is not known. It is the type-safe counterpart of
any. You can assign anything to an unknown type.
-e.g.
let unknownVar:unknown;
unknownVar = true; //boolean
unknownVar = 10; //number
unknownVar = 10n; //BigInt >>=ES2020
unknownVar = "Hello World"; //String
unknownVar = ["1","2","3","4"] //Array
unknownVar = {firstName:'', lastName:''}; // Object
unknownVar = null; // null
unknownVar = undefined; // undefined
unknownVar = Symbol("key"); // Symbol

-But cannot assign unknown to any other types.


e.g. let value: unknown;
let value1: boolean = value; // Error
let value2: number = value; // Error
let value3: string = value; // Error
let value4: object = value; // Error
let value5: any[] = value; // Error
let value6: Function = value; // Error
#Primitive Types
-TypeScript supports 7 primitive types number, string, boolean, bigint, symbol, undefined, and
null. All other data types are objects in Typescript. A primitive data type is a data type that is not
an object and has no methods. All primitives are immutable.
• String
We use the string data type to store textual data. The string value is enclosed in double-quotes (“)
or single quotes (‘).
• Multiline string
The strings can span multiple lines in such cases the strings are surrounded by the
backtick/backquote (`) character
• Null and Undefined
JavaScript has two ways to refer to the null. They are null and undefined and are two separate
data types in Typescript as well. The null and undefined are subtypes of all other types. That
means you can assign null and undefined to something like a number.
e.g. let u: undefined = undefined;
let n: null = null;
-undefined Denotes value is given to all uninitialized variables.
null: Represents the intentional absence of object value.
• Symbol
The symbol is the new primitive type introduced in ES6 and represents the javaScript symbol
primitive type. it represents unique tokens that may be used as keys for object properties. it is
created by the global Symbol() function. Each time the Symbol() function is called, a new unique
symbol is returned.
#TypeScript Objects
-Everything that isn’t a Primitive type in TypeScript is a subclass of the object type. Objects
provide a way to group several values into a single value. You can group any values of other
types like string, number, booleans, dates, arrays, etc. An object can also contain other objects.
-A Typescript object is a collection of key-value pairs. Each key-value pair is known as a
property, where the key is the name of the property and value its value.
e.g. let person = {
firstName: "Allie",
lastName: "Grater",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
#Type Annotations in TypeScript
-Typescript uses type annotation to specify the data type of the variable, function, object, or
function return value. It uses the syntax :[type], where type is the Typescript type. Once you have
annotated an identifier to be of a certain type, you can only use it as that Type. The Typescript
compiler throws an error if you use the identifier as a different type.
-Types are the reason why typescript exits. We annotate a variable, function, function return
value, etc to let the compiler know how we intend to use it. we use the syntax :[type], where type
is the Typescript datatype.
• Using the Type Annotation
-We annotate a variable by using a colon (:) followed by its type. There can be a space after the
colon. For example, the following shows how to use the type annotation in variable declaration.

-The types are optional in Typescript. If you do not want to use the types, then annotate them
with any.
-Examples of Type Annotation
• Arrays
-The arrays are annotated using the string[] or Array as shown in the example below.
e.g. var cities: string[] = ['Delhi', 'New York', 'London'];
//OR
var cities: Array<string> =['Delhi', 'New York', 'London'];
• Function arguments & Return Types
Here, the function arguments are annotated with the number data type and so is the return type.
e.g. function add(x: number, y: number): number {
return x + y;
}
• Anonymous Objects
Here, we are creating a object with two properties. The properties are annotated with the type
number & string.
e.g. var student: { id: number; name: string; };
student = { id: 100, name : "Rahul" }
• Union types
The union types are special. They allow a variable to be of either of two types. In the example,
the id can be either a string or a number. The Typescript allows you to perform both string &
arithmetic operations on the variable id.
e.g. var id: string|number
#Typescript Variable
-A Typescript variable is a storage for the data, where programs can store value or information.
-Declaring the variable
We need to declare the variables before using them. We use let, var or const keyword to declare
the variable.
-Naming the Variable
• Variable name must be unique within the scope.
• The first letter of a variable should be an upper case letter, Lower case letter, underscore
or a dollar sign
• Subsequent letters of a variable can have upper case letter, Lower case letter, underscore,
dollar sign, or a numeric digit
• They cannot be keywords.
• Identifiers are case-sensitive.
• They cannot contain spaces.
-Variable Declaration syntax
We can declare the variables in four different ways.
• Both type and Initial value
Here, we define both the type and initial value of the variable.
Syntax:
let [Indentifier] : [type-annotation] = value ;
var [Indentifier] : [type-annotation] = value ;
const [Indentifier] : [type-annotation] = value ;
e.g. var message: string = "Hello World"
var num: number =1000;
console.log(message);
console.log(num);
• Only the type
Only the type is declared. Variable will get the value undefined. The const is not allowed here.
Syntax:
let [Indentifier] : [type-annotation];
var [Indentifier] : [type-annotation];
//const is not allowed without an initial value
e.g. var message: string
var num: number
console.log(message); //will print undefined as no value is assigned
console.log(num);
message="Hello World"
num=1000;
console.log(message);
console.log(num);
O/P: undefined
undefined
Hello World
1000
• Only the initial value
Here, the variables are defined without type, but with an initial value. The Typescript infers the
type from the value assigned to it.
Syntax:
let [Indentifier] = value;
var [Indentifier] = value;
const [Indentifier] = value;
e.g. var message = "Hello World" //Typescript infers the type as string becasue assigned value
is string
var num =1000; //num is a number because 100 is assigned to it
console.log(message);
console.log(num);
message = num;
• Without type and initial value
Here neither the type nor the initial value is given. In this case, the compiler infers the type as
any. The const keyword not allowed here.
Syntax:
let [Indentifier]; //type is assumes the type as any.
var [Indentifier]; //type is assumes the type as any.
//const is not allowed without an initial value.
e.g. var message
var num
message = "Hello World"
num =1000;
console.log(message);
console.log(num);

#Typescript Keywords
Keywords have a special meaning in the context of a language. The following table lists some
keywords in TypeScript.
-Reserved words:
break case catch
class const continue
debugger default delete
do else enum
export extends false
finally for function
If import in
istanceOf new null
return super switch
this throw true
try typeOf var
void while with

#Variable Scope in TypeScript : Global, Local & function


-The scope of a variable determines which part of the program can access it. We can define a
variable in three ways, so as to limit their visibility.
-One is the local variable or block variable, which has the scope of a code block (block scope or
local scope). The second one is a function variable or class variable which has the function/class
scope. The last one is the global variable, which can be accessed anywhere in the program
(global scope).
-The Typescript variable can be in three scopes depending on how & where you have defined
them.
• Global Scope
Define the global variable outside of any function/ class or code block and they become part of
the global scope. We can use them anywhere within the program.
e.g. let GlobalVar=100;
function someFn() { //function
console.log(GlobalVar)
if (true) { //code block
console.log(GlobalVar)
}
function nested() { //nested function within someFn1
console.log(GlobalVar)
}
}
• Function Scope
The function or class variables defined inside the function/class etc are function scoped. They are
available to use anywhere within the function. You cannot use them outside the function.
e.g. function someFn() {
//Variable defined inside the function.
//can be accessed from anywhere inside the function
//including the nested function or code block
let fnVar=10
console.log(fnVar) //can be accessed here
if (true) {
console.log(fnVar) //can be accessed here
}
function nested() {
console.log(fnVar) //can be accessed here
}
}
e.g.2. Nested function
The example below defines a fnNestedVar inside the nested function. We can access this variable
only within the nested function and its nested functions and code blocks. But not from the parent
function or anywhere outside the nested function.
function someFn() {
if (true) {
}
function nested() {
//defined inside nested function
//can be accessed only within the nested function and its nested functions & code blocks
let fnNestedVar=100
console.log(fnNestedVar)
}
console.log(fnNestedVar) //cannot be accessed here
}
function someOtherFn() {
console.log(fnNestedVar) //cannot be accessed here
}
for (let c = 0; c < 3; c++){
console.log(fnNestedVar); //cannot be accessed here
}
console.log(fnNestedVar)
• Local scope or Block Scope
The local variables are declared inside a code block. They are also known by the name block
variable. The code block is a section of source code clearly delimited using the curly braces. For
example inside the if/try/catch/while/for block.
e.g. function someFn() {
if (true) {
//defined locally
//Its scope ends where curly braces ends
let localVar=1000
console.log(localVar) //ok
}
console.log(localVar) //Error
• var is an exception
-The keyword var is an exception to the above rule. var supports only global & function scope.
So if you define a variable inside a code block, it is scoped to enclosing function and not to the
code block
-That is the main reason why let exist. To bring the local scope to the Javascript. The let is part of
the ES2015 or ES6 specification.
e.g. function someFn() {
if (true) {
//defined locally using var, which is function scoped
//You can access it any where within the someFn
//This is the major difference between var & let
var localVar=1000
console.log(localVar) //ok
}
console.log(localVar) //ok
function nested() {
console.log(localVar) //ok
}
}
#Declaring the variable
-There are three keywords, that you can use to declare a variable in Typescript. They are let, var
or const keyword. The scoping rules differ between them.
-The var supports function & global scopes as shown in the example above.
-The let & const support all three scopes.
#Difference between Let vs Var vs Const
• Variable Scope:
-var is function scoped
The variables declared using var inside the function are available only within that function. If we
declare them outside the function, then they are available everywhere i.e. they are a global
variable.If we define them inside a code block, they are still scoped to the enclosing function.
-let & const is block scoped
The variables declared using let or const are block-scoped. They are scoped to the block in which
they are declared i.e. inside the if/try/catch/while/for or any code block (enclosed in curly
parentheses).
This means that we can only use it in the code block where we declare them. Outside the code
block, they are invisible
If they are outside the code block, but within the function body then they become function
scoped.
If they are outside the function and code block, then they are available globally or become a
global variable.
• var variables can be redefined or updated
-We can update or redefine a var variable.
e.g. var MaxTry=10;
console.log(MaxTry);
var MaxTry=100; //No Error here even if we are declaring it again
console.log(MaxTry);
-The let or const variables cannot be redeclared or updated within the same scope.
• Var can be accessed before they are declared
-We can access the var variable, even before we declare them(Because variable declarations (and
declarations in general) are processed before any code is executed, declaring a variable anywhere
in the code is equivalent to declaring it at the top). This is called variable hoisting.
• Const cannot be reassigned
We must declare a const variable with an initial value. The value cannot be reassigned again.
#let, var & const. Which one to choose?
-Now, we know the difference between let, var & const. So the question is which one will you
choose.
-Const is always the first choice, if the value of the variable does not change once initialized.
This will prevent some programmers from accidentally modifying the value, which can happen if
you use var or let
-let is the choice of all other variables. Because let & const are block-scoped. You do not have to
worry about variables declared in for loop or if the statement is being overwritten outside the
block. block scope helps us to identify bugs and makes our code easier to read.
-Avoid var. The var can be redefined, can be reassigned, and does not support block scope. This
makes the code harder to read & debug.
NOTE: Operators from the link given above.
• ==(Loose Equality Operator): It checks whether the values of the two operands are equal
or not. If the operands are of different types, then it does a type conversion before
comparing
Example:
let a = 10;
let b = 10;
let c = "10";
console.log(a==b); //true
console.log(a==c); //true
• ===(Strict Equality Operator): It checks whether the type and values of the two operands
are equal or not.
Example:
let a = 10;
let b = 10;
let c = "10";
console.log(a===b); //true
console.log(a===c); //false

Flow Control Statements


#Typescript if, else & nested if statement
-If statement
syntax :
if (condition) {
//(Conditional code / if block)
//Statements to execute if Condition is true
}
-If Else Statement
Syntax:
if (condition) {
//if Block
//Statement to execute if Condition is true
} else {
//Else Block
//Statement to execute if Condition is false
}
-Multiple conditions using else if
Syntax: if (condition1) {
//If Block1
//Statement to execute if Condition1 is true
} else if (condition2) {
//If Block2
//Statement to execute if Condition2 is true
} else if (condition3) {
//If Block3
//Statement to execute if Condition3 is true
} else {
//Else Block
//Statement to execute if all the above conditions are false
}
-Nested if
Synatx:
if (condition1)
{
//Executes when condition1 is true
if (condition2)
{
//Executes when both condition1 & condition2 is true
if (condition3)
{
//Executes when both condition1 & condition3 is true
}
}
else if (condition4)
{
//Executes when both condition1 & condition4 is true
}
}

#Functions in TypeScript
-A TypeScript function is a block of code that performs a specific task or calculates a value.
-A function declaration starts with a function keyword. It is followed by a list of parameters and
then followed by statements inside curly braces {…}.
-Syntax:
function name(param1[:type], param2[:type], param3[:type]) [: returnType] {
[statements]
}
-e.g.
function calcArea(width:number, height:number):number {
let result= width * height;
return result;
}
let area=calcArea(10,5)
console.log(area)
-

You might also like