Skip to content

Commit 8fd89a7

Browse files
authored
Merge pull request #946 from priyavratamohan/main
Adding more sections to TypeScript
2 parents a20a72c + 97f7133 commit 8fd89a7

10 files changed

+1028
-2
lines changed

docs/javascript/basic-js.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,4 +115,4 @@ The `document.getElementById().innerText` method is used to write into an HTML e
115115
:::info
116116
**Before moving to the next section, make sure you have a basic understanding of the above concepts.**
117117
You can use any of the above methods to display the output in JavaScript.
118-
:::
118+
:::

docs/typescript/advanced-types-ts.md

+96
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
---
2+
id: advanced-types-ts
3+
title: Advanced Types in TypeScript
4+
sidebar_label: Advanced Types in TypeScript
5+
sidebar_position: 8
6+
tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide]
7+
description: A Description of Advanced Types in TypeScript
8+
---
9+
10+
In this section, you'll delve into advanced TypeScript types, which enable you to express more complex relationships between data structures and provide additional tools for type safety and flexibility in your code.
11+
12+
## 1. Intersection Types
13+
14+
Intersection types allow you to combine multiple types into one, creating a type that possesses all the properties and methods of each constituent type.
15+
16+
Example -
17+
18+
```tsx title='typescript'
19+
interface Dog {
20+
bark(): void;
21+
}
22+
23+
interface Cat {
24+
meow(): void;
25+
}
26+
27+
type Pet = Dog & Cat;
28+
29+
class DogImpl implements Dog {
30+
bark(): void {
31+
console.log("Woof! Woof!");
32+
}
33+
}
34+
35+
class CatImpl implements Cat {
36+
meow(): void {
37+
console.log("Meow! Meow!");
38+
}
39+
}
40+
41+
function makePet(): Pet {
42+
return new DogImpl() as Pet;
43+
}
44+
45+
let pet: Pet = makePet();
46+
pet.bark(); // Output: Woof! Woof!
47+
pet.meow(); // Output: Error: Property 'meow' does not exist on type 'Pet'.
48+
```
49+
50+
## 2. Type Guards
51+
52+
Type guards are runtime checks that allow TypeScript to infer more specific types within certain code paths, enhancing type safety and enabling more precise type checking.
53+
54+
Example -
55+
56+
```tsx title='typescript'
57+
function isNumber(x: any): x is number {
58+
return typeof x === "number";
59+
}
60+
61+
function processValue(value: string | number): void {
62+
if (isNumber(value)) {
63+
console.log(value * 2);
64+
} else {
65+
console.log(value.toUpperCase());
66+
}
67+
}
68+
69+
processValue(10); // Output: 20
70+
processValue("hello"); // Output: HELLO
71+
72+
```
73+
74+
## 3. Type Casting
75+
76+
Type casting allows you to assert the type of a value, informing TypeScript's type system of your intent and enabling you to perform operations that require a specific type.
77+
78+
Example -
79+
80+
```tsx title='typescript'
81+
let someValue: any = "hello";
82+
let strLength: number = (someValue as string).length;
83+
console.log(strLength); // Output: 5
84+
```
85+
86+
## 4. Type Assertions
87+
88+
Type assertions provide a way to override TypeScript's type inference and explicitly specify the type of a variable, giving you more control over type checking and enabling you to work with external data sources or dynamic values.
89+
90+
Example -
91+
92+
```tsx title='typescript'
93+
let someValue: any = "hello";
94+
let strLength: number = (someValue as string).length;
95+
console.log(strLength); // Output: 5
96+
```

docs/typescript/classes-ts.md

+246
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
---
2+
id: classes-ts
3+
title: Classes and Inheritance in TypeScript
4+
sidebar_label: Classes and Inheritance in TypeScript
5+
sidebar_position: 6
6+
tags: [TypeScript, Introduction to TypeScript, TypeScript Basics, TypeScript Introduction, TypeScript Overview, TypeScript Tutorial, TypeScript Guide, TypeScript Getting Started, TypeScript Introduction Tutorial, TypeScript Introduction Guide, TypeScript Introduction Getting Started, TypeScript Introduction Overview, TypeScript Introduction Basics, TypeScript Introduction Basics Tutorial, TypeScript Introduction Basics Guide, TypeScript Introduction Basics Overview, TypeScript Introduction Basics Getting Started, TypeScript Introduction Basics Getting Started Tutorial, TypeScript Introduction Basics Getting Started Guide]
7+
description: A Description of Classes and Inheritance Rules used in TypeScript
8+
---
9+
Classes are a fundamental feature of object-oriented programming (OOP) that provide a blueprint for creating objects with predefined properties and methods. In TypeScript, classes offer a powerful way to structure your code, encapsulate data, and organize functionality in a modular and reusable manner.
10+
11+
**Using classes in TypeScript allows you to:**
12+
13+
***1. Encapsulate Data:*** Classes allow you to encapsulate related data and behavior into a single unit, promoting code organization and maintainability.
14+
15+
***2. Define Blueprints for Objects:*** With classes, you can define blueprints or templates for creating objects with consistent structures and behaviors.
16+
17+
***3. Implement Inheritance:*** TypeScript supports inheritance, allowing classes to inherit properties and methods from parent classes, enabling code reuse and promoting the principle of DRY (Don't Repeat Yourself).
18+
19+
***4. Utilize Access Modifiers:*** TypeScript provides access modifiers such as public, private, and protected, which allow you to control the visibility and accessibility of class members, enhancing data encapsulation and security.
20+
21+
***5. Implement Abstraction:*** Abstract classes and methods enable you to define common behaviors and structures without providing a concrete implementation, fostering modular design and extensibility.
22+
23+
***6. Utilize Static Members:*** Static members belong to the class itself rather than to any specific instance, providing a convenient way to define utility functions or shared data.
24+
25+
In this section, you will explore various class-related concepts such as classes, access modifiers, the readonly modifier, getters & setters, inheritance, static methods & properties, and abstract classes, and learn how to use them effectively in your TypeScript programs.
26+
27+
## 1. Classes
28+
29+
Classes are blueprints for creating objects with predefined properties and methods. They encapsulate data and behavior, providing a clear structure for your programs.
30+
31+
Example:
32+
33+
```tsx title='typescript'
34+
class Person {
35+
name: string;
36+
age: number;
37+
38+
constructor(name: string, age: number) {
39+
this.name = name;
40+
this.age = age;
41+
}
42+
43+
greet(): void {
44+
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
45+
}
46+
}
47+
48+
let person = new Person("Alice", 30);
49+
person.greet(); // Output: Hello, my name is Alice and I am 30 years old.
50+
```
51+
52+
## 2. Access Modifiers
53+
54+
These modifiers control the visibility of class members, enhancing encapsulation and protecting data.
55+
The three types of access possible in TypeScript are private, protected, and public access modifiers.
56+
57+
Example:
58+
59+
```tsx title='typescript'
60+
class Employee {
61+
public name: string; // accessible from anywhere
62+
private salary: number; // accessible only within the class
63+
protected department: string; // accessible within the class and subclasses
64+
65+
constructor(name: string, salary: number, department: string) {
66+
this.name = name;
67+
this.salary = salary;
68+
this.department = department;
69+
}
70+
71+
public getDetails(): void {
72+
console.log(`${this.name} works in the ${this.department} department.`);
73+
}
74+
75+
private getSalary(): number {
76+
return this.salary;
77+
}
78+
}
79+
80+
class Manager extends Employee {
81+
constructor(name: string, salary: number, department: string) {
82+
super(name, salary, department);
83+
}
84+
85+
public getManagerDetails(): void {
86+
console.log(`${this.name} is a manager in the ${this.department} department.`);
87+
}
88+
}
89+
90+
let manager = new Manager("Bob", 80000, "HR");
91+
manager.getDetails(); // Output: Bob works in the HR department.
92+
// manager.getSalary(); // Error: Property 'getSalary' is private and only accessible within class 'Employee'.
93+
manager.getManagerDetails(); // Output: Bob is a manager in the HR department.
94+
```
95+
96+
## 3. The readonly Modifier
97+
98+
Use the readonly modifier to make class properties immutable. Once assigned, the value of readonly properties cannot be changed, ensuring that certain critical properties remain constant.
99+
100+
Example:
101+
102+
```tsx title='typescript'
103+
class Car {
104+
readonly make: string;
105+
readonly model: string;
106+
year: number;
107+
108+
constructor(make: string, model: string, year: number) {
109+
this.make = make;
110+
this.model = model;
111+
this.year = year;
112+
}
113+
114+
displayDetails(): void {
115+
console.log(`${this.year} ${this.make} ${this.model}`);
116+
}
117+
}
118+
119+
let car = new Car("Toyota", "Corolla", 2020);
120+
car.displayDetails(); // Output: 2020 Toyota Corolla
121+
car.year = 2021;
122+
car.displayDetails(); // Output: 2021 Toyota Corolla
123+
// car.make = "Honda"; // Error: Cannot assign to 'make' because it is a read-only property.
124+
```
125+
126+
## 4. Getters & Setters
127+
128+
Getters and Setters allow you to control the access of the class properties. They enable the encapsulation of data, providing controlled access and modification of properties.
129+
130+
Example:
131+
132+
```tsx title='typescript'
133+
class Circle {
134+
private _radius: number;
135+
136+
constructor(radius: number) {
137+
this._radius = radius;
138+
}
139+
140+
get radius(): number {
141+
return this._radius;
142+
}
143+
144+
set radius(value: number) {
145+
if (value <= 0) {
146+
throw new Error("Radius must be positive.");
147+
}
148+
this._radius = value;
149+
}
150+
151+
getArea(): number {
152+
return Math.PI * this._radius * this._radius;
153+
}
154+
}
155+
156+
let circle = new Circle(5);
157+
console.log(circle.radius); // Output: 5
158+
circle.radius = 10;
159+
console.log(circle.getArea()); // Output: 314.159...
160+
// circle.radius = -5; // Error: Radius must be positive.
161+
```
162+
163+
## 5. Inheritance
164+
165+
Learn how to use inheritance to reuse the functionality of another class. Inheritance allows you to create a new class based on an existing class, extending its properties and methods.
166+
167+
Example:
168+
169+
```tsx title='typescript'
170+
class Animal {
171+
name: string;
172+
173+
constructor(name: string) {
174+
this.name = name;
175+
}
176+
177+
move(distance: number = 0): void {
178+
console.log(`${this.name} moved ${distance} meters.`);
179+
}
180+
}
181+
182+
class Dog extends Animal {
183+
bark(): void {
184+
console.log("Woof! Woof!");
185+
}
186+
}
187+
188+
let dog = new Dog("Rex");
189+
dog.bark(); // Output: Woof! Woof!
190+
dog.move(10); // Output: Rex moved 10 meters.
191+
```
192+
193+
## 6. Static Methods & Properties
194+
195+
Define static methods and properties shared by all instances of a class. Static members belong to the class itself rather than to any specific instance, making them useful for utility functions or shared data.
196+
197+
Example:
198+
199+
```tsx title='typescript'
200+
class MathUtil {
201+
static PI: number = 3.14;
202+
203+
static calculateCircumference(radius: number): number {
204+
return 2 * MathUtil.PI * radius;
205+
}
206+
}
207+
208+
console.log(MathUtil.PI); // Output: 3.14
209+
console.log(MathUtil.calculateCircumference(10)); // Output: 62.8
210+
```
211+
212+
## 7. Abstract Classes
213+
214+
Explain the abstract classes that define some common behaviors. Abstract classes cannot be instantiated directly and are meant to be extended by other classes, providing a base structure and forcing implementation of specific methods.
215+
216+
Example -
217+
218+
```tsx title='typescript'
219+
abstract class Shape {
220+
abstract getArea(): number;
221+
222+
display(): void {
223+
console.log(`The area is ${this.getArea()}`);
224+
}
225+
}
226+
227+
class Rectangle extends Shape {
228+
width: number;
229+
height: number;
230+
231+
constructor(width: number, height: number) {
232+
super();
233+
this.width = width;
234+
this.height = height;
235+
}
236+
237+
getArea(): number {
238+
return this.width * this.height;
239+
}
240+
}
241+
242+
let rectangle = new Rectangle(5, 10);
243+
rectangle.display(); // Output: The area is 50
244+
```
245+
246+
These concepts and examples illustrate how to effectively use classes and their advanced features in TypeScript, enhancing your ability to write robust and maintainable object-oriented code.

0 commit comments

Comments
 (0)