Typescript Tutorial
Typescript Tutorial
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.
-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
#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)
-