Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

TypeScript Tutorial

Typescript is a free and open-source programming language developed and maintained by Microsoft. We can think of typescript as the wrapper around JavaScript with extra features like strict type, interface and class, and modules to JavaScript.

The browser can’t run typescript, we have need compile typescript to javascript so that browser can run the Javascript language.

  1. Basic Data type or built-in data type in typescript.
  2. User Define data type in Typescript

TypeScript support two type of variable, we have primitive types include the number, Boolean, null, undefine, void, array, enum and object types can include modules, classes, and interfaces. The TypeScript allows us to declare the type of a variable as optional is known as optional static type notation. For a variable, the type notation comes after the variable name and is preceded by a colon:

Defining unknow type
var test; // unknown type
In preceding code, we can assign test as any type, it becomes a dynamic type and we can assign any type to variable test.

var num;
num =20;
num ="hi";

console.log(num);

// Output hi

num = 12.39;
console.log(num);

// Output 12.39

Assigning new type value to unknown type will not generate any error by Typescript compiler.

Define data type any : Any data type is the supertype of all types in TypeScript. It denotes a dynamic type. Using any type is equivalent to opting out of type checking for a variable.

var num: number;
num =20;
num ="Namasta";
console.log(num);
//OP - Namasta

Define variable Type inference: TypeScript’s type inference feature that automatically infers a variable’s type based on the assignment.
var num1 = 0; // number (Inferred)
var val = “Namase”; // String (Inferred)

TypeScript will try to guess the type of the variable by examining the assigned values. For example of above code, the Typescript will identify the num1 as number type.

Define variable type:  In Typescript, allow us to define variable type explicitly,

var num: number =20;
num ="Namasta";
console.log("Value of number is "+num);
//OP TypeScript- main.ts(18,1): error TS2322: Type '"Namasta"' is not assignable to type 'number'

TypeScript basic datatype we have number, boolean, string, array, enum and so on.

let isVisible: boolean = true;  // Boolean Type

// Implicitly typed variable

let isVisible = true;
isVisible = "hidden"; 

// ERROR: string not assignable to type boolean

// Declaration and assignment split: Without type

let isVisible2;
isVisible2 = true;
isVisible2 = "hidden"; // WORKS, as type cannot be infered

// Declaration and assignment split: With type

let isVisible3: boolean;
isVisible3 = true;
isVisible3 = "hidden"; // ERROR: string not assignable to type boolean

Number
Numbers in TypeScript are of type number:
let width: number = 2;

The TypeScript is a superset of JavaScript. In TypeScript, we don’t have the separate type for integer, short, float and all numbers are 64-bit floating point numbers. That means you can also assign a number of decimals to your variable:
let width: number = 5.12;

TypeScript also supports number-literals in the form of hex, binary and octal. These four number-variables contain all the same value, 27:

let dec: number = 27;
let hex: number = 0x001b;
let binary: number = 0b11011;
let octal: number= 0o0033;

String: To create a string-variable, we can use the string-type in TypeScript. You can put the assigned string in double-quotes or in single-quotes. We can include string literals in Typescripts by enclosing them in single or double quotation marks. TypeScript also supports template strings by using back-ticks instead of quotes and we can also include expressions in such a template string by using the syntax ${ expression } in your string:

let firstName: string ="Arjun";
let message: string = `Namasta  ${firstName}, how are you?`;

// We can also include line break 

let message: string = `Namasta ${firstName},
how are you?`;

Array:  TypeScript allows you to work with arrays of values. Array types can be written in one of two ways. In TypeScript, we can declare an array using square bracket syntax. In the first method, you use the type of the elements followed by ‘[]’ to denote an array of that element type.

let arr : number[] = [74, 46, 32];
let arr : Array<number> = [72, 89,21];

Iterating Array :
We can iterate value of an array using for-of-loop and for-in-loop. For in TypeScript is similar to for of loop, where for in-loop on an array does not return the values themselves but the index of all the values.

let names: string[] = ["Arjun", "Kumar", "Rahul"];

for (let tname of tnames) {
    console.log(name);
}

for (let index in names) {
    console.log(`${index} - ${names[index]}`);
}

Tuple: Tuples are like an array of mixed type with the limited number’ of the item.

let student : ['Ratan', 43]; // Tuple array with mixed type

let address : [string, number] = ["Green Park", 99];
console.log(address[0]);
console.log(address[1]);

Operation on Tuple:  Tuples in TypeScript supports various operations like an array, pushing a new item,  removing an item from the tuple, etc.

var address = ["Green Park", "Delhi", 10]; 
console.log("Items before push "+address.length)    // returns the tuple size 

address.push(12)                                    // append value to the tuple 
console.log("Items after push "+address.length) 
console.log("Items before pop "+address.length) 
console.log(address.pop()+" popped from the tuple") // removes and returns the last item
  
console.log("Items after pop "+address.length)

Enum: A very helpful addition to the standard set of the datatype, Typescript also support is the ‘enum’. An ‘enum’ is an easy way of giving friendly names to sets of numeric values.

enum Color { Yellow, Blue, Red, White }
let color:Color = Color.Blue;
console.log(typeof color); // number
console.log(color);   //1
console.log(Color[color]);  // Blue

By default, enums begin numbering their members starting at 0. We can change this by manually setting the value of one its members.  For example, we can start the previous example at 1 instead of 0.

enum Color {green = 1, yellow, red};
enum Color {red = 1, yellow = 2, brown = 4};
TypeScript Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top