0% found this document useful (0 votes)
5 views13 pages

Type Script

This document provides comprehensive notes on TypeScript, covering essential concepts such as type declarations, type inference, functions, and custom data types using types and interfaces. It explains the differences between various TypeScript features, including generics, enums, and access modifiers in classes. Additionally, it highlights important questions related to TypeScript for further understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Type Script

This document provides comprehensive notes on TypeScript, covering essential concepts such as type declarations, type inference, functions, and custom data types using types and interfaces. It explains the differences between various TypeScript features, including generics, enums, and access modifiers in classes. Additionally, it highlights important questions related to TypeScript for further understanding.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

TypeScript Notes: Sudhanshu Kumar

Important - make sure a file is created which is [Link] which is created with tsc --init
which help to convert the js to ts and also make sure ts-node and typescript globally install
which is installed using this command -
npm install -g typescript
npm install -g ts-node

TypeScript uses compile time type checking. This means it checks if


the specified types match before running the code, not while
running the code.
TypeScript being converted into JavaScript means it runs anywhere
that JavaScript runs!

● TypeScript is not another way of programming language, but they are the
wrapper over javascript, a superset of javascript or we can say that It is a
development tool for javascript. So, remember the TS is not a programming
language.
—----------------------------------------------------------------------------------------------------
● The syntax for declaring the variables -
let myNum:number=8890.8899; // this is explicit
let secondNum = 9888; // this is implicit and they detect automatic
But in these two variables, it is not required to declare dataType the TS
detects from itself is it dataType it is known as inference or infer. So, do’t
declare the datatype during the variable initialization.

When creating a variable, there are two main ways TypeScript assigns a type:

● Explicit
● Implicit

TypeScript may not always properly infer what the type of a variable
may be. In such cases, it will set the type to any which disables type
checking.

// Implicit any as [Link] doesn't know what type of data


it returns so it can be "any" thing...

const json = [Link]("55");

// Most expect json to be an object, but it can be a string


or a number like this example

[Link](typeof json);
unknown is a similar, but safer alternative to any.

unknown is best used when you don't know the type of data being typed. To
add a type later, you'll need to cast it.

Casting is when we use the "as" keyword to say property or variable is of the
casted type.

never effectively throws an error whenever it is defined.

undefined and null are types that refer to the JavaScript primitives
undefined and null respectively.

—----------------------------------------------------------------------------------------------
● The any is not datype but it is marker that show the variable does not assign
with the dataType. Let’s take an example for that -

let hero;
function myHero(){
return “Iron Men”;}
hero(show any) = myHero();

Here, the hero variable shows any because they are not type-checked. For
type checking, we assign the data type during the initialization of the variable.
let hero: string;
—--------------------------------------------------------------------------------------------

During the Function creation, the parameter of the function also shows any so we
could strict dataType in the following way-

function myFun(name:String){
return name;}

myFun(34); /////////////////// Incorrect because they accept String


myFun(“Sudhanshu”);

For default value -

function myFun(name:String, email:string = “ksudhanshu394@[Link]”){


return name;}

If you want to restrict the return type of function then -

function myFun(name:String):String{
return “Hello World”; // the function must be return string because here the return
type is String
}

For arrow function

const myFun=(name:string):string=>{
Return “Hello Wolrd”;
}

Let’s take a scenario -

function predicate(name:String, age:number){


if(age>18){
return true;
}
else{
return “Not Valid Age”;
}
}

Here in this example, the return type is based on condition. So, we can not strict
condition here. So, we learn more about later

For strict type in map function -

const myArr=[12,23,34,45,55];

[Link]((data):number=>{
return data; // here we restrict return data type with number but the TS automatically
detect that they return number because the myArr is number. They are useful when
the return type is different from iterable things.
})

For Void functions -

Function smallFun(name:string):void{
[Link](“Hello”); // here is no return type so we use void return type
}

For Never return function -


The never return type is used for when no return type, they used for termination of
function and throw error.
—------------------------------------------------------------------------------------------------------------
type is basically used for creating the custom datatype, let’s take and example for
that -

type myObj={
name:string;
email:string;
address:string
}

function showUserDetails(user:myObj):void{
[Link]([Link] + [Link] + [Link])
}

—------------------------------------------------------------------------------------------------

Code for readonly, optional and join (&)

type myDetails = {
readonly id: Number;
name: String;
address: String;
phone?: Number // through question mark the phone property
becomes optional

const data: myDetails = {


id: 811583,
name: "Sudhanshu",
address: "Lucknow",
phone: 99185649 // this is optional
}

[Link] = "Jannat";
// [Link]=99999; can not do because it is read only
[Link]([Link])

// LET'S MAKE ANOTHER TYPE DATA FOR SEEING THE JOIN


type professionalInfo = {
work: String,
salary: String,
companyName: String
}

type combineDetails = myDetails & professionalInfo &


{ officeJoinDate: String } // this is joining the all type data

// now using the data


const fullDetails: combineDetails = {
id:88,
name: "Sudhanshu Kumar",
address: "Lucknow",
phone: 8115830551,
work: "Software Engineer",
salary: "1 Cr",
company_Name: "Paytm",
offixeJoinDate: "29 Feb 2024"
}

export { };

Uniary (|) in Typescript -

// UNION IS USED WHEN WE DO NOT KNOW WHAT DATATYPE COMES AND WHEN
MULTIPLE DATATYPE WANTS IT IS DENOTED BY (|)

function validAge(name: String, age: Number): boolean | String {


// here we can return boolean value to string value
if (age == 18) {
return true;
}
else {
return `${name} Not Valid Age`;
}
}

validAge("Sudhanshu", 18);
const myDetails: (Number| String)[] = ["Sudhanshu Kumar",887];

[Link](myDetails)
export { };

Tuples in TypeScript -

// TUPLE IS BASICALLY USED FOR GETTING THE VALUE IN SPECIFIC


ORDER OF DEFINED THAT AND THEY HAVE NO SPECIAL SINGLE

let details:[String, number,


boolean]=["Sudhanshu",8115830551,true];
// in this details array ke have to assign a value in specific
order otherwise they provide error

// PROBLEM IN TUPLES

// in tuples we can break this by using a data type using push(),


shift() etc.

[Link](67); // they add 67 in 0 index of array but


according to tuple they accept string used string in that place

Interface in Typescript -

// INTERFACE IS ALSO SIMILAR TO "TYPES'' IN TYPESCRIPT. USING


THIS WE COULD MAKE CUSTOM DATA TYPE SIMILAR TO "TYPE". WE TALK
ABOUT DIFFERENCES LATER

interface users {
name: String,
email: String,
phone: Number,
completeDetails(age: number): string
}

let myPersonalInfo: users = {


name: "Sudhanshu",
email: "ksudhanshu394@[Link]",
phone: 8115830551,
completeDetails: function (age) {
return `Name : ${[Link]} Email : ${[Link]} Phone :
${[Link]} Age : ${age}`;
}
}

export {}

Using ‘private’ and “public” keywords in class Of Typscript -

Private - makes a class property private, they are accessed only it’s scope or
we can say that within a class. In JavaScrit it is declared using the # keyword.
The method of class also become private same as making private properties .

Public - make a class properties public, which is accessible overall the


program. By default it’s public

Protected - for making a method and properties protected of class, we could


only use protected keyword same as private and public. The protected could
only accessible by own class and ite’s inheritance class. Nothing different from
javacsript.

class myClass {
readonly id: string = "sudhanshu29";
private salary: number = 100000;
name: string;
email: string;
phone: number
constructor(name, email, phone) {
[Link] = name;
[Link] = email;
[Link] = phone;

[Link] = [Link];
}
}

const makeObj = new myClass("Sudhanshu",


"ksudhanshu394@[Link]", 8115830551);

for (let x in makeObj) {


[Link](myClass[x])
}

export { };

Getter and Setter In Typescript -

Getter (get) and setter (set) is similar as javascript but one difference is that
we could not set dataType return in setter, remember that. Other is similar to
javascript.

For returning objects -

For returning objects we used {}, let’s take an example -

function myFun(name:string, email:string, phone:number):{}{


return {name, email, phone};
}

Difference Between interface and Types In TypeScript -

Mainly Interface and Types is used for making custom dataType of formate we
can say that formate of DataType, the main difference are -

● In Interface, we could easily add the properties and methods. Let’s take
an example -
interface commonRols{
name:string,
phone:number,
address:string
}

interface commonRols{
salary:number,
Id:number,}
const peopleDetails:commonRols={
name:”Sudhanshu Kumar”,
phone:8115830551,
address:”Lucknow”,
salary:800000,
id:29
}

In this example we could easily join properties with same name of


interface.

● The second main difference is that, we could easily extend the


properties from another interference, just like in class. Let’s take an
example for that -

interface commonRols{
name:string,
phone:number,
address:string
}

interface admin extends commonRols, multiple interference also come{


adminId:string,
companyName:string,
}

const admin:admin={
name:”Sudhanshu Kumar”,
phone:8115830551,
address:”Lucknow”,
adminId:”sudhanshu29”,
companyName:”edusmartly”
}

In this example, we have to inherited the properties form commonRols


interference to admin interference.

Abstract Class In TypesScript -

Through Abstract class we could not create object from that, but we
could define a class for it’s inherited class and you want that some
methods in abstract class is must be used then add abstract keyword
before method, and if you want optional then do’t add abstract keyword
before method.
Here is the example for that -

abstract class formateDetails {


constructor(public name: string, public email: string,
public address: string, public phone: number, public age:
number) {

abstract drivingProg(): void; // this is required


optionalMethod(): string{ // remember the optional must
be define immediately, they would not defined as abstract
method "just remember"
return "This is optional";
}
}

class useAbstract extends formateDetails {


constructor(public name: string, public email: string,
public address: string, public phone: number, public age:
number) {
super(name, email, address, phone, age);
}

drivingProg(): void {
[Link]("I am Testing a Code....");
}
}

const makeObj = new useAbstract("Sudhnashu Kumar",


"ksudhanshu394@[Link]", "Lucknow", 8115830551, 18);

export { };

Generices In TypeScript -

Generices in TypeScript means setting the dynamic dataType, here is the


example below -

function myFun<Type>(name:Type):Type{
return name;
}

// or we can also write in short form (generics is basically


used for dynamic dataType conversion)
myFun("Sudhanshu");

function shortFormGeneric<T>(id:T):T{
return id;
}

const x = shortFormGeneric(29);
[Link](x);
export {};

Using Generics With Array Through Normal And Arrow Function -

function arrayGeneric<Type>(data: Type[]): Type {


return data[2];
}// using generics in normal function of array

const arrowArrGenerics = <Type>(data: Type[]): Type => {


return data[0];
} // generics in arrow function

const myArr = [12, 23, 34, 45, 56, 67, 78];


const result = arrayGeneric(myArr);

[Link](result);

const arrow_fun_result = arrayGeneric(myArr);


[Link](arrow_fun_result);

export { };

An enum is a special "class" that represents a group of constants


(unchangeable variables).

Enums come in two flavours string and numeric


Numeric Enums - Default
enum StatusCodes {

NotFound = 404,

Success = 200,

Accepted = 202,

BadRequest = 400

// logs 404

[Link]([Link]);

// logs 200

[Link]([Link]);

The implements use when we want to inherit the


properties and methods of instance to class, let's
take an example for that -

interface Shape {

getArea: () => number;

class Rectangle implements Shape {

public constructor(protected readonly width: number,


protected readonly height: number) {}

public getArea(): number {

return [Link] * [Link];

}
}

const myRect = new Rectangle(10,20);

[Link]([Link]());

Most Important Questions


● how to handel null and unknown in ts
● what is difference between null and undefined
● how any is better than unkown in ts
● what is tuple in easy way in ts
● what is type in ts
● What is difference Between Type and Interface

Solution - [Link]
9a22-132d3cc3ec65

You might also like