TypeScript Basics

Introduction:

TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. TypeScript extends JavaScript by adding static typing, object-oriented features, and other enhancements that help improve the development experience and catch potential errors at compile-time.

  • WHAT IS TYPESCRIPT
    • TS is enhanced version of Javascript.
    • We can also say that TS is superset of Javascript.
    • TS is build on javascript.
    • TS is first converted in JS and then it execute.
    • TS can not directly run on the browser
    • TS compiler first convert the code from TS to Javascript
  • TS is an enhanced version of JavaScript.
  • We Could say superset of javascript.
  • TypeScript is building on JavaScript.
  • TS is not a new Language. this is just to add some new features in JS.
  • TYPESCRIPT BENEFIT
    • Check error on compile time
    • Datatype can be define on TS like string,number, bool etc.
    • We can add object-oriented way with TS
  • VERSION AND HISTORY
    • Developed By Microsoft
    • First release is 1 oct -2012
    • Influenced by Javascript
    • 5.1.6/ 5 July 2023

Key features of TypeScript include:

    1. Static Typing:
       - TypeScript introduces static typing, allowing developers to specify types for variables, function parameters, and return values.
       - Static typing helps catch type-related errors during the development phase, before the code is executed.

    2. Object-Oriented Programming (OOP) Support:
       - TypeScript supports object-oriented programming concepts such as classes, interfaces, inheritance, and access modifiers.
       - It allows developers to write modular and structured code using familiar OOP principles.

    3. Enhanced Tooling and Developer Experience:
       - TypeScript provides a rich set of tooling, including autocompletion, type checking, code navigation, and refactoring support.
       - These tools enable developers to catch errors early, improve code quality, and enhance productivity.

    4. ECMAScript Compatibility:
       - TypeScript is designed to align with the latest ECMAScript (JavaScript) standards.
       - It provides support for modern JavaScript features and syntax, even before they are supported in all browsers.

    5. Gradual Adoption:
       - TypeScript allows existing JavaScript projects to be gradually migrated to TypeScript by incrementally adding type annotations and using TypeScript features.
       - JavaScript code can be mixed with TypeScript code, allowing developers to leverage TypeScript's benefits without requiring a complete rewrite.

    6. Strong Community and Ecosystem:
       - TypeScript has gained significant popularity and has a vibrant community.
       - It has a large ecosystem of libraries and frameworks built specifically for TypeScript development.

Installing and Importance

  • Download node and install.
    • Download from https://nodejs.org and install on default folder.
  • Install TS
    • npm install -g typescript //(-g is used for globally installation)
  • Checkout TS is working fine.
    • tsc -v //to check currect version
  • An example why TS is important.
    • Create a folder ts-test and open this is in terminal
    • create a test.ts file within this folder
      • function add(a:number,b:number){

return a+b

}

add(10,5)

  • on terminal write command to compile: tsc test.ts
  • this will create a new file test.js which is complitly a JS file as

function add(a,b){

return a+b

}

add(10,5)

  • create index.html

Setting Up Editor

  • VS Code editor is recommended.
  • install some important plugin for VS.
    • Spellcheck
    • prettier
  • Interview Question

First Program

  • MAKE FIRST PROGRAM
  • Make TypeScript file.
    • Create app.ts file
    • put below code:
      • const num:number= 10

console.log(num)

  • Generate JS file.
    • tsc app.ts
  • Make an HTML file and add js file here.
    • Create index.html
    • add app.js in index.html
  • Run program on the browser.
    • Go on browser and open index.html
    • 10 will show in console.
  • Interview Questions

Core Data Types

  • What are Core Data Types:
    • Number
    • String
    • Boolean
  • Interview Questions
    • What are core datatypes of TS?
      • Number
        • Can store number and float values
      • String
        • Anything within single quote or double quote will become as string either they are integer for any true/false value
      • Boolean
        • true and false value
    • If we assign any other datatype value and try to convert TS file to JS file, this will through error.

TypeScript vs JavaScript

  • In TS
    • function sum(num1:number,num2:number){

return num1+num2;

}

sum(10,20);

  • In Javascript
    • function sum(num1,num2){

if(typeof num1 ===’number’ && typeof num2===’number’){

return num1+num2;

} else {

return new Error(‘num1 and num2 are not of same datatype.’);

}

}

Type inference in typescript

  • What is Type inference in typescript
    • In TS, when we first define any variable, then not need to define Type of that varible. TS auto detect according to assigned value. This is called Type Inference.
    • A variable can auto detect the type of variable according to their value.
  • Example
    • var txt = ‘sd’; // txt has datatype string
    • var txt2 = 5; // txt2 has datatype number
    • const txt3 = 5; // txt3 has datatype 5 because we can’t change value of const

Object Type in typescript

  • What is Object Type in typescript
    • const person:object = {};
  • How to Make object type
    • const person:{name:string;age:number,email:string}={

name: ‘Sunil’,

age: 27,

email:’test@gm.com’

}

  • How to reuse object Type

type objType = {name:string;age:number,email:string};

const person:objType={

name: ‘Sunil’,

age: 27,

email:’test@gm.com’

}

const person2:objType={

name: ‘Sunil’,

age: 27,

email:’test@gm.com’

}

  • Interview Questions
    • How to creat an object type
    • What is object type?
    • How to create object type

Array Type in typescript

  • What is Array Type in typescript
  • How to Make array type
    • let arr:string[] = [‘php’,’net’,’phython’]
    • let arr2:any[] = [‘php’,123,false] //if not clear the types within an array
    • let arr3:[string,number,boolean] = [‘php’,123,false] // if limited array
  • How to reuse array Type
  • Interview Questions

Tuple Type in typescript

  • what is Tuple in typescript
  • how to Make Tuple type
    • let arr3:[string,number,boolean] = [‘php’,123,false]
  • How to reuse Tuple Type
  • Interview Questions
    • What is differenc in Tupple and array in TS?
      • Homogeneous Elements: Arrays are collections of elements with the same data type.
      • Heterogeneous Elements: Tuples can store elements of different data types. Each element in a tuple can have a different type from the others.
      • Dynamic Length: Arrays are dynamic in length
      • Fixed Length: Tuples have a fixed length,
      • Methods: Arrays come with built-in methods like push, pop, splice, etc., to manipulate their content easily.
      • Limited Methods: Tuples have fewer built-in methods compared to arrays since they are not designed for dynamic manipulation. However, we can use array methods on tuples after converting them.

Enum in TypeScript

  • enum Type in typescript
  • A Group Of constant
  • That can assign a number to your string and make an easy comparison.
  • enum Role {values}
    • enum Role {

ADMIN,MANAGER,READ_ONLY_USER

}

Any in TypeScript

  • why we use any type in typescript
    • we use this when we don’t know what will be datatype.
    • let data:any = 10;
    • let data:any[] = [10,11];
  • the advantage in any type
  • disadvantage of any type

Union in TypeScript

  • why we use union type in typescript
    • If we have doubt on datatype then we use union type
  • the advantage in union type
    • let data :number | integer = ‘ad’;
  • example of any type
    • let data :number | integer = ‘ad’;

Literals in TypeScript

  • why we use Literals type in typescript
    • Apply values rather than apply types to a variable or parameter
  • the advantage in Literals type
  • example of Literals type
    • let data:’abc’ | 123 = ‘abc’;

Type Alias in typescript

  • Define Type like a variable and reuse it
  • Type Alisa with variable
    • create a variable with type and reuse this

type objType = {name:string;age:number,email:string};

const person:objType={

name: ‘Sunil’,

age: 27,

email:’test@gm.com’

}

const person2:objType={

name: ‘Sunil’,

age: 27,

email:’test@gm.com’

}

  • Type Alisa with function params

Function Type

  • What is function type
    • Return type of a function is called function type.
  • Why we need function type
    • We need function type to force a function to return a specific datatype
  • How to define function type
    • function add():number

{

return 100; // when we define any string the TS Compiler through error.

}

  • Interview Question
    • Can a function type will be undefined?
      • Yes

Void function

  • What does Void means?
    • When a function does not return any value then that is void type.
  • How to define void.
    • fuction printData(){

console.log(‘Test’);

}

  • Use of void.
    • fuction printData():void

{

console.log(‘Test’);

}

  • By default if function does not return anything then it is void type.

unknown Type in TS

  • What is an unknown type?
    • If we don’t know datatype of any variable, then we can use unknown
  • How this is different from any?
    • any and unknown, both are doing same role but unknown is more secure then any
    • Ex:

data=20;

data=’hellow’;

let item:string;

item=data; // if data has type known, then it will through error, but if data has type any then if will not through any error because datatype are switched in case of any but not switched in case of known

data=20;

data=’hellow’;

let item:string;

item=data; // if data has type known, then it will through error, but if data has type any then if will not through any error because datatype are switched in case of any but not switched in case of known

Never Type

  • What is never type?
    • If a function did not return then it is never type of function. Void type function is return undefined
  • How this is different from void?
    • void return undefined and never did not return any type.
  • Example?
    • fuction apiError(msg,code):never

{

throw {message:msg,apiCode:code}

}

console.log(apiError(‘test error’,200))

Compile and Use Multiple Files

  • How to use multiple file
    • import all files using script tag as we already using.
  • How to compile multiple files
  • Generate ts config file?
    • tsc -init
    • on success, tsconfig.json file is created
    • tsc -w //will compile all the TS file to JS file
  • Interview Question.
    • What is use of tsconfig.json?

Include and Exclude file folder

  • How to exclude file?
    • In tsonfig.json file, add “exclude”:{}, and put the file name which need to excluded on compile with tsc -w
    • exclude”:{file_1,file_2}
  • How to exclude the folder?
    • exclude”:{file_1,file_2,folder_1}
    • exclude”:{

“file_1”,

“file_2”,

“folder_1”,

“*/test.ts” // will exlude this file which is in any folder

}

  • How to include file?
    • include”:{file_1,file_2,folder_1}
  • How to include folder?
    • include”:{

“file_1”,

“file_2”,

“folder_1”,

“*/test.ts” // will exlude this file which is in any folder

}

target Configuration

  • What is target config?
    • In tsconfig.json file, we can change ecmascript version
    • In ES5, let and const is converted in var, but in ES6, it is converted in let and const in JS file after compiling.
  • Use of target?
    • To change the ecmascript version
  • Example
    • IF ES5 set
      • let num:number=100;

const item=”Test”;

  • After Compile, JS File has

var num=100;

var item=”Test”;

  • IF ES6 set
    • let num:number=100;

const item=”Test”;

  • After Compile, JS File has

let num=100;

const item=”Test”;

  • Target maintain the ES Version.

rootDir and outDir

  • Output in a specific folder?
    • outDir is used to define where all compiled JS file will be store
  • Target a specific fonder
    • rootDir is used to define, only TS files from rootDir will be compiled in outDir
  • Interview Question.
    • Other TS file will not compile, if rootDir is mentioned.
    • In this case Error is getting to define location for other TS file
    • To Resolve this error, we can put rootDir in include:[rootDir]

Code Quality improvement Options

  • noUnusedLocals: true => used to highlight unused variables in TS.
  • noUnusedParameters: true => used to highlight unused parameters in TS functions.
  • noImplicitReturn: true => used to highlight part of code which does not return anything.
  • strictNullChecks: true => used to highlight part of code which does not return anything.
  • noFallthroughCasesInSwitch : true => used to highlight the switch case if break is not mentioned.

Class basic

  • A class is a user-defined data-type that describes what a certain type of object is.
  • We can also say that a class is a datastructure.
  • We can define property and methods in class.
  • After compiling, TSC will create new complex JS file.
  • Ex:
    • class Users{

name:’’,

email:’’

addUser(user){

return `${user} is added.`;

}

}

let User1 = new Users;

let result = User1.addUser(‘Anil’);

console.log(‘result: ’,result)

YouTube player

Class Compilation with ES5 and ES6

when we compile any TS file then it target to a specific ES Version.

  • how to change compilation target
    • Target Version can be changed from tsconfig.json which has target key.
    • By
  • compile with ES5
    • ES5 does not support Ops concept, so it compile if pure JS file
  • compile with ECMAScript 6
    • ES6 support classes like structure
    • And seams similer compiled file like TS File.

Public and Private access modifiers

  • What are access modifiers?
    • Access modifiers are concept of Ops to handle accessibility of properties and functions.
  • Why need access modifiers?
    • Using this we can put properties will be accessible withing a class or outside of a class.
  • Public access modifier.
    • If access modifier is public then we can use properties inside class or outside of that class.
  • Private access modifier.
    • If access modifier is private then we can use properties inside class.
  • Protected access modifier.
    • If access modifier is protected then we can use properties inside currect child class.
  • Interview Question

Constructor and Shorthand Initialization

  • Understand constructor.
    • Constructor are method in class which is automaticaly called when we create object of that class.
  • Apply shorthand initialization
    • class Users{
        } const u1 = new Users(‘Anil’,25,’test@t.com’);

    read only vs private property

    • Diff. b/w Read only and Private
      • Rean only proprty can be accessible outside of a class but can’t be update, while private property can be accessible only inside the class and can be update.
    • Example of read only
      • class Users{
          }

      const u1 = new Users();

      console.log(u1.name)

      Inheritance in TS with example

      • What is inheritance
        • Using properties of one class in other class is called inheritance.
      • Make parent class
        • The class which properties is used is called parent class.
      • Make child class
        • The class where we use other class properties is called chiled class.
      • Use inheritance
        • we can use inheritance using extends keyword.
        • Ex: class Users extends CreateAccount{ }