What Typescript is?
====================
-TypeScript is a strongly typed, object oriented, compiled language.
-TypeScript is both a language and a set of tools.
-TypeScript is a typed superset of JavaScript compiled to JavaScript.
-TypeScript is JavaScript plus some additional features.
Javascript TypeScript
---------------------------------------------------------
1.strongly typed-No 1.strongly typed-yes
2.directly run on browser 2.not directly run on the browser
3.classes, interfaces, 3.classes,interfaces,inheritance,generics
inheritance, generics-No
4.optional parameters-No 4.optional parameters-yes
5.interpreted language 5.compiles the code
6.errors at runtime 6.errors during the development time
7.modules-no 7.modules-yes
8.generics-no 8.generics-yes
Environment Setup
==================
-The TypeScript compiler is itself a .ts file compiled down to JavaScript (.js)
file.
-The TSC (TypeScript Compiler) is a source-to-source compiler (transcompiler /
transpiler).
-TypeScript Compiler(TSC generates a JavaScript version of the .ts file passed to
it.
-TSC produces an equivalent JavaScript source code from the Typescript file given
as an input to it.
This process is termed as transpilation.
-compiler rejects any raw JavaScript file passed to it.compiler deals with only .ts
files.
1. download Nodejs and install
https://nodejs.org/en/download/
2. check nodejs is installed
node -v (in command prompt)
3. install Typescript
npm install -g typescript
4. create a TS file(abc.ts), compile the file using the below command, and expect a
JS file
tsc abc.ts (abc.js will be generated)
node abc.js
abc.ts --> tsc abc.ts --> abc.js
Note − Multiple files can be compiled at once.
tsc file1.ts, file2.ts, file3.ts
Compiler Flags
==============
-Compiler flags enable us to change the behavior of the compiler during
compilation.
--help Displays the help manual
--module Load external modules
--target Set the target ECMA version
--declaration Generates an additional .d.ts file
--removeComments Removes all comments from the output file
--out Compile multiple files into a single output file
--sourcemap Generate a sourcemap (.map) files
--watch Watch for file changes and recompile them on
the fly
--module noImplicitAny Disallows the compiler from inferring the any type
Datatypes
=========
number Function
string Class
boolean Touple
null Enum
undefined Interface
void Object
TypeScript - Type Annotations
==============================
var age: number = 32; // number variable
var name: string = "John";// string variable
var isUpdated: boolean = true;// Boolean variable
We can declare a variable in one of the four ways:
1. Declare type and value in a single statement
var [identifier] : [type-annotation] = value;
2. Declare its type but no value. In this case, the variable will be set to
undefined.
var [identifier] : [type-annotation];
3. Declare its value but no type. The variable type will be set to the data type of
the assigned value
var [identifier] = value;
4. Declare without value and type. The datatype of the variable will be any and
will be initialized to undefined.
var [identifier];
any unknown
======================================================
1. any turns off type checking(Unsafe) 1. Safe (forces type checks)
2. Can be assigned to anything 2. Can only be assigned after
type check
3. When type safety is not a concern 3. type is unknown but must be checked
before use
let a: any;
let b: number = a; // No error
let x: unknown;
let y: number = x; // error
var let const
===================================================================
1.since begining 1.ECMASCRIPT-6(2015) 1.ECMASCRIPT-6(2015)
2.value can be changed 2.value can be changed 2.cann't be changed
3.initialization is 3.initialization is 3.mandatory
not mandatory not mandatory
4.can be redeclared 4.cann't be redeclared 4.cann't be redeclared
5.hoisting-yes 5.hoisting-no 5.hoisting-no
6.function scope 6.block scope 6.block scope
variable Hoisting:
------------------
-In hoisting, variables and function declarations are moved to the top of
their enclosing scope before code execution.
-we can use a variable before it is declared.
-only variable declaration is hoisted, variable value is not hoisted.
-variable hoisting is done only for 'var' variables not for let/const.
console.log(a);
var a = 10;
var a;
console.log(a);
a = 10;
variable scope:
---------------
Global Scope − Global variables are declared outside the programming constructs.
These variables can be accessed from anywhere within your code.
Class Scope − These variables are also called fields.
Fields or class variables are declared within the class but outside the
methods.
These variables can be accessed using the object of the class.
Fields can also be static.
Static fields can be accessed using the class name.
Local Scope − Local variables are declared within the constructs like methods,
loops etc.
Local variables are accessible only within the construct where
they are declared.
Operators
==========
1. arithmetic (+,-,*,/,%,**) /quotient %remainder **exponent
2. Assignment (=,+=,-=)
3. Relational (>,>=,<,<=,==,===,!=,!==)
4. logical (&&,||,!)
5. bitwise (&,|,^,~)
6. increment/decrement (++,--)
7. miscelaneous (typeof,instanceof)
Functions
=========
1. Function Declaration
2. function Expression
3. IIFE
4. Arrow
-Optional Parameters
-Rest Parameters
-Default Parameters
-Recursion
-Parameter type Inference
-Pure Function
-Function Overloading
OOPS
*****
-A programming language is called OOPL if that supports the below 4 features.
1. Encapsulation
2. PolyMorphism
3. Inheritance
4. Abstraction
-Java,C#,typescript,Python
class - structure/blueprint/template for creating Object
class has only logical existance
class doesn't have physical existance
object - every instance of a class
Object has physical existance
a class generally contains the below things
-variables / data-members
-functions / member-functions
-constructor
Constructor
===========
-A constructor is a special function of the class that is responsible for
initializing the variables of the class.
-TypeScript defines a constructor using the constructor keyword.
-constructor gets invoked every time object is being created for a class.
-A constructor is a function and hence can be parameterized.
-The this keyword refers to the current instance of the class.
1. Default Constructor
2. No-arguement Constructor
3. parameterized Constructor
Access Specifiers
=================
-TypeScript supports access modifiers at the class level.
-TypeScript supports three access modifiers - public, private, and protected.
Public - By default, members (properties and methods) of TypeScript class are
public.
you don’t need to prefix members with the public keyword.
Public members are accessible everywhere without restrictions.
Private - A private member cannot be accessed outside of its containing class.
Private members can be accessed only within the class.
Protected - A protected member cannot be accessed outside of its containing class.
Protected members can be accessed only within the class
and by the instance of its sub/child class.
private - inside the same class
protected - inside the same class, child class
public - inside the same class, child class , outside the class
data-Hiding
============
-Hiding the data from outside world.
-it can achieved by declaring the data-members private.
-private members of a class cann't be used outside.
-inter-class communication- Not
Encapsulation
=============
- declare your data-members private, but declare public methods using which
other classes can communicate with you.
- Encapsulation = datahiding + getters & setters
getter: This method comes when you want to access any property of an object.
setter: This method comes when you want to change any property of an object.
Static
======
-static members are shared members accross all the objects
-only one copy of static members will be created and shared accross all the
objects.
-nonstatic members of a class are accessed with object.
-static members of a class are accessed with ClassName, as they are not part of any
particular object.
- static : className.memberName
- nonstatic : objectName.memberName
Readonly
========
-Readonly is used to make a property as read-only(constant).
-Readonly members can be accessed outside the class, but their value cannot be
changed.
PolyMorphism
============
-poly = many
-morphism = form
-polymorphism- 1. static (Method Overloading)
2. dynamic/Runtime (method overriding) (Inheritance)
-When child class declares a method which is already there in parent class,that is
overriding
-when child class is not satisfied with parent class method logic, child class
declares
one more method with the same name but differnt logic
Inheritance
===========
-Inheritance provides the ability to create a new class from an existing class.
-acquires the properties and behaviors of a class from another class.
-The class whose members are inherited is called the base/super/parent class.
-the class that inherits those members is called the derived/subclass/child.
-TypeScript uses class inheritance through the extends keyword.
-Used for Code Reusability
-TypeScript supports only single and multilevel inheritance.
-It doesn't support multiple, hierarchical, and hybrid inheritance.
Super
=====
-parent class constructor cann't be invoked before child class constructor is
invoked.
-if there is a child class, child class is responsible to call parent class
constructor
- by using super();
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.
-We cannot instantiate the interface, but it can be referenced by the class object
that implements it. The TypeScript compiler uses interface for type-checking (also
known as "duck typing" or "structural subtyping") whether the object has a specific
structure or not.
-The interface contains only the declaration of the methods and fields, but not the
implementation.
-We cannot use it to build anything.
-It is inherited by a class, and the class which implements interface defines all
members of the interface.
-When the Typescript compiler compiles it into JavaScript,
then the interface will be disappeared from the JavaScript file.
Thus, its purpose is to help in the development stage only.
Interface Types
====================================================================
1. Define Object Structure 1. for unions, intersections
2. can extend another interface 2. extensible using intersection ( type
Employee = Person & {role:string} )
3. No union types 3. union (Ex:type Status =
"success" | "error" | "loading")
Generics
========
-Generics are defined using angle brackets (<T>)
-Generics are powerful when you want to write code that works with different data
types without losing type safety.
-They allow the creation of reusable components, functions, and data structures
without sacrificing type checking.