Skip to content

Instantly share code, notes, and snippets.

@gajjardarshithasmukhbhai
Last active March 24, 2023 19:51
Show Gist options
  • Save gajjardarshithasmukhbhai/e3d9d0431522642cef742dc0433e1809 to your computer and use it in GitHub Desktop.
Save gajjardarshithasmukhbhai/e3d9d0431522642cef742dc0433e1809 to your computer and use it in GitHub Desktop.
TypeScript is very Important when you are worked on the enterprise level of application. You will learn in this module are integrate the TypeScript with the React Js and Node Js

Introduction and Installement of Type Script

  • What is The Type Script and How it's different

68747470733a2f2f692e696d2e67652f323032322f30372f30342f75556b7673632e706e67

68747470733a2f2f692e696d2e67652f323032322f30372f30342f75556b6852792e706e67

For Installing the TypeScript You have need below things

  • you need install TypeScript Globally before run the TypeScript Code
sudo npm install -g typescript
  • Compiling the TypeScript File into JavaScript we need to Compiler so it convert TS file to JS file
>tsc <------- this command used to convert TypeScript File into JavaScript File

68747470733a2f2f692e696d2e67652f323032322f30372f30342f75686c7369342e706e67

Data Types

  • const {variable name}: {variable type} = {variable value}
  1. Number Data Type ts const myNum: number = 1207;

  2. Array Data Type

  • specific Number Declared
const myArr: Array<number> = [12, 90, 71];```

- If the data types inside the array are unknown or a mixture of data types, the array can be declared using the <any> type (this is a type all on it's own that is discussed below):

```ts const myArr: Array<any> = [12, 'thirteen', false];
  • If you want to return number in function so You will do this manner
function numCheck(): number {
  return 91;
}
  1. For Object We are Doing this manner
let team: Data = {
  names: ["hello", "Darshit"],
  hobbies: ["games", "book", "painting"],
  output: (test) => {
    return test + this.hobbies;
  },
};
  • JavaScript uses "dynamic types" (Resolved at runtime), TypeScript uses "static types" (set during development)
Type Script Object Declaration
const person: {} = {
  name: "Darshit",
  age: 32,
};

[--OR--]

const person = {
  name: "Hasmukh",
  age: 34,
};

Above Snippet is not Good Practice

const person: {
  name: string;
  age: number;
} = {
  name: "Darshit",
  age: 32,
};
Tuple in Type Script
  • Tuple is tightly coupled Array. If you mentioned limited array type so you will not add more. so one kind of you also set the length of the array.
const person: {
    name: string,
    company: string,
    position: string,
    expectationCtc: number,
    role: [number,string]
} = {
    name: "Darshit",
    company: "virtusa",
    position: "Engineer of Technology",
    expectationCtc: 25,
    role: [22, "Test"] // Also You Follow the Order wherever you mention in object
}
person.role = [32,"ssdd","ddd"]; |-> It Throw the Error Because it hamper the length of the role that are mentioned on above
  • push method is exception of the tuple means you are able to add object more that mentioned lengh Ex.
person.role.push("sjkhs"); /-> It works Perfectly point be note
All Types in Type Script

68747470733a2f2f692e696d2e67652f323032322f30372f30352f75696a734e312e706e67

Union Types in Type Script
  • Below is the Union method so we use both parameter like number and String
function combine(param1: number | string, param2: number | string) {
  if (typeof param1 === "number" && typeof param2 === "number") {
    return param1 + param2;
  }
  return `${param1.toString()} ${param2.toString()}`;
}
console.log(combine(11, 22));
console.log(combine("Darshit", "Gajjar"));
Literal Types in Type Script
function combine(
  input1: number | string,
  input2: number | string,
  input3: "as-number" | "as-text"
) {
  console.log("input1", input1);
  console.log("input2", input2);
  console.log("input3", input3);
}
combine("Darshit", "Gajjar", "as-number");
  • In input3 if we are passing other thank 'as-number' or 'as-text' so it throw the Error.
  • For that time string literal very useful
Types Aliases Custom Types
type StringNumberCombinable = string | number;
type CustomCombinable = "as-Number" | "as-Next";

function concatTwoValue(
  input1: StringNumberCombinable,
  input2: StringNumberCombinable,
  input3: CustomCombinable
) {
  if (typeof input3 === "as-Number") {
    return input1 + input2; //-> Error Under Monitoring
  }
  return false;
}
concatTwoValue(12, 22, "as-Number");
Function Return Types
function add(value1: number, value2: number): number {
  return value1 + value2;
}
add(22, 32);
Function as Types
function add(number1:number,number2: number) {
    return number1+number2;
}
let combineValue: (a:number,b:number) => number;
combineValue = add;

console.log(combineValue(12,22)); // Output 34
Function Types & Callbacks
  • In addHandler after 22 value is not callback function
  • in AddHandler we mention function difinition in as parameter
function addHandler(value1: number, value2: number, cb: (num: number) => void) {
  let result = value1 + value2;
  cb(result);
}
addHandler(12, 22, (result) => {
  console.log("result: ", result);
});
Unknown is Better than the Any
  • Unknown Type before assign the value first it will check the value Type then after it will assign the value
  • and Unknown not all every values, it will allow certain types
  • instead of Any allow the all the types
let userName: unknown;
let userPassword: string;

userName = "darshitHGAaja";
userPassword = "2872@@@873181";
userPassword = userName; //  userName type is unknown so it will not assign to the userpassword
// so assigning unknown value to string we need to check first then after we will assign
console.log(typeof userName);
if (typeof userName === "string") {
  userPassword = userName;
}
Never use in TypeScript
  • Never is used for standard enterprise term
  • Let say if you want not return something so for that you used Never Type in TypeScript
  • we will use void for that but as standard way we will use Never use
let something: void = null;
let nothing: never = null; // Error: Type 'null' is not assignable to type 'never'

function throwError(errorMsg: string): never {
  throw new Error(errorMsg);
}

function keepProcessing(): never {
  while (true) {
    console.log("I always does something and never ends.");
  }
}

Advanced Java Script Concepts

Fat Arrow Function Used
const add = (a: number, b: number) => a + b;
const printOutput = (output: number) => {
  console.log("My Output", output);
};

printOutput(add(5, 2));
Spread Operator in Java Script
const hobbies = {
  name: "darshit",
  subject: "computer science",
  ctc: "12 lpa",
};
const newHobbies = { ...hobbies, manType: "male" };
console.log("newHobbies: ", newHobbies);
Rest Operator in Java Script
const sumAllValue = (...operator: number[]) => {
  return operator.reduce((previousValue, currentValue) => {
    return previousValue + currentValue;
  }, 10);
};

const sum = sumAllValue(11, 12, 13, 14);
console.log("sum: ", sum); // sum:60
Creating A First Class in TypeScript
  • Creating the First Class in TypeScript
class Department {
  name: string;
  constructor(n: string) {
    this.name = n;
    console.log("My Name is Khan", this.name);
  }
}
const accounting = new Department("Acconting vala Bhai");
console.log(accounting);
Constructor Function and this keyword
class Department {
  name: string;
  constructor(n: string) {
    this.name = n;
  }
  describe(this: Department) {
    return this.name;
  }
}

const accounting = new Department("Hi Darshit!");
accounting.describe(); // this weill display Output
const accountInfo = { name: "Dummy", describe: accounting.describe }; // but if you doing accountInfo.describe -> It will display Undefined
console.log("accountInfo: ", accountInfo.describe()); // accountInfo: Dummy
private and public identifier define in class
class Department {
  private employeeId: string;
  private employeeName: string;
  public companyWiseEmployeeNames: {
    companyName: string;
    employeeName: string;
  }[] = [];
  constructor(name: string) {
    this.employeeName = name;
  }
  addEmployee({ id }) {
    this.employeeId = id;
  }
  getEmplyeeInfo(): string {
    return `My Employee ID is ${this.employeeId}. My Name is ${this.employeeName}`;
  }
  addEmployeeCompanyWise(addComWithEmpName) {
    this.companyWiseEmployeeNames.push(addComWithEmpName);
  }
  getCompanyEmployees() {
    return this.companyWiseEmployeeNames;
  }
}
const person = new Department("Darshit");
person.addEmployee({ id: "12EDx23" });
person.addEmployeeCompanyWise({
  companyName: "E-Delta",
  employeeName: "Darshit Gajjar",
});
person.addEmployeeCompanyWise({
  companyName: "Virtusa",
  employeeName: "Darshit Gajjar",
});

// If you not define so by default it is consider as the public
person.companyWiseEmployeeNames.push({
  companyName: "Mandiant",
  employeeName: "Darshit Gajjar",
}); // This Became True if and only if you're variable is object

console.log(person.getCompanyEmployees()); // [ { companyName: 'E-Delta', employeeName: 'Darshit Gajjar' }, { companyName: 'Virtusa', employeeName: 'Darshit Gajjar' },{ companyName: 'Mandiant', employeeName: 'Darshit Gajjar' } ]
console.log(person.getEmplyeeInfo()); // My Employee ID is 12EDx23. My Name is Darshit
private readOnly Identifier
class Department {
  private readonly employeeName: string; // This kind of Extra thing make your code more clear either work on big team or after come back to couple of weeks. so this is Best Practices
  constructor(name: string) {
    this.employeeName = name;
  }
  getEmplyeeInfo(): string {
    return `My Name is ${this.employeeName}`;
  }
}
const person = new Department("Darshit");
console.log("Hi", person.getEmplyeeInfo());
Interface in TypeScript
interface IsPerson {
  name: string;
  age: number;
  speak(a: string): string;
  spendMoney(a: number): number;
}
const m: IsPerson = {
  name: "Darshit",
  age: 22,
  speak: (name: string): string => {
    console.log("Test");
    return name;
  },
  spendMoney: (myNumber: number): number => {
    console.log("success");
    return myNumber;
  },
};
console.log("My Name:>", m.speak("Darshit GAjjar")); // My Name:> Darshit GAjjar

const getMyInfo = (info: IsPerson) => {
  console.log(info.speak("Darshit Gajjar")); // Hi Gajjar Darshit Gajjar
};
const iSpeak = (name: string): string => {
  return `Hi Gajjar ${name}`;
};
const mySpendingMoney = (number: number): number => {
  return number;
};
getMyInfo({
  name: "Darshit Gajjar",
  age: 45,
  speak: iSpeak,
  spendMoney: mySpendingMoney,
});
multiple Interface implement in Class
  • Interface not give conckrit example, But through Interface you will be able to multiple interface implment in class.

  • In class if you use interface, so we have add some more function and variables. so It give more freedom. But with freedom you have to use method and variables that mentioned in class.

  • Beauty of Interface is we use in Various classes

  • Interface super powerful If certain method want to use in strict manner ex. we have one method that is super useful and we are used in various classes so that time, this Interface super helpful to strickly follow that method

interface Person {
  empName: string;
  setPersonName(name: string): void;
}
interface GetUserInfo {
  getUserName(): string;
}
class Employee implements Person, GetUserInfo {
  organisationName: string;
  empName: string;

  constructor(org: string) {
    this.organisationName = org;
  }
  setPersonName(name: string): void {
    this.empName = name;
  }
  getUserName(): string {
    return `${this.empName} work in ${this.organisationName}`;
  }
}
const user = new Employee("Virtusa");
user.setPersonName("Darshit Gajjar");
console.log(user.getUserName());
Read Only Interface Functionality
  • Read only Functionality super useful, When you are not want to modify variable value in externally, so that time it work like charm. so It prohibated to user to modify it's value.
interface Person {
  readonly empName: string;
  setPersonName(name: string): void;
}
interface GetUserInfo {
  getUserName(): string;
}
class Employee implements Person, GetUserInfo {
  organisationName: string;
  empName: string;

  constructor(org: string) {
    this.organisationName = org;
  }
  setPersonName(name: string): void {
    this.empName = name;
  }
  getUserName(): string {
    return `${this.empName} work in ${this.organisationName}`;
  }
}
const user = new Employee("Virtusa");

user.setPersonName("Darshit Gajjar");
user.empName = "DarshitGajjar"; // It throw the Error like use haven't assign the value because it's read-only properties.

console.log(user.getUserName());
Multiple Interface use Together
  • we have multiple class Application
    • class1 need only name
    • class2 need name and firstName
    • class3 need name,firstName and lastName
  • So in this scenario we have to use the multiple Interface together ex.

Screenshot 2022-08-21 173115

Interface for Class Method

Screenshot 2022-08-21 174309

optional in TypeScript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment