-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.ts
More file actions
373 lines (298 loc) · 8.97 KB
/
Copy pathapp.ts
File metadata and controls
373 lines (298 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Tuples
let arr: [number, string] = [12, "Nikhil"];
// Enums
enum UserRoles {
ADMIN = "admin",
GUEST = "guest",
SUPER_ADMIN = "super_admin",
}
UserRoles.ADMIN;
enum StatusCode {
ABDANDONED = "Abdandoned status code 500",
NOTFOUND = "Not Found status code 404",
}
StatusCode.ABDANDONED;
let a; //let a: any;
a = 12;
a = "Nikhil";
//a agar string hai then ok, but when a is num, there's an error, but it doesn't give error in type any, so used type unknown
a.toUpperCase();
//Type Inference | Type Annotation
let b: number; //Here type is defined | known as Type Annotation
let c = 12; // Type Inference, means value ko dekh kar, type khud pata karle
//Interfaces and Type Aliases
//@ Defining interfaces
//@ Using interfaces to define object shapes
interface User {
name: string;
email: string;
password: string;
gender?: string; //Optional property
}
function getDataOfUser(obj: User) {}
getDataOfUser({
name: "Nikhil Shrivastava",
email: "nikhil.shrivastava304@gmail.com",
password: "nikhil-304",
});
//@ Extending interfaces
interface User2 {
name: string;
email: string;
password: string;
gender?: string; //Optional property
}
interface Admin extends User2 {
admin: boolean;
}
function abcd(obj: Admin) {
// obj.(name | email | password | gender);
obj.admin;
}
//@ Type aliases
type sankhya = number;
let abc: sankhya;
type value = string | number | null;
let ak: value; //let ak: string | number | null;
//@ Intersection types
type UserIntersection = {
name: string;
email: string;
};
type AdminIntersection = UserIntersection & {
getDetails(user: string): void;
};
function abcde(a: AdminIntersection) {}
//@Classes & Constructor
class HumanMaker {
constructor(
public name: string,
public surname: string,
public isHandsome: boolean
) {}
}
let h1 = new HumanMaker("Nikhil", "Shrivastava", true);
//@Classes & Constructor -> "this" keyword
class BottleMaker {
public name;
constructor(name: string) {
this.name = name;
}
}
let b1 = new BottleMaker("Milton");
// @Classes & Constructor -> "Public and Private" access modifier
class BottleMaker2 {
constructor(
public /*| private -> it'll show error, but it'll run*/ name: string
) {}
}
class MetaBottleMaker extends BottleMaker2 {
constructor(name: string) {
super(name);
}
getValue() {
console.log(this.name);
}
}
let b2 = new MetaBottleMaker("Cello");
b2.getValue();
// @Classes & Constructor -> "Protected" access modifier
class BottleMaker3 {
protected name: string = "Milton";
// Protected access modifier provides same features like private, but with a twist, that it can be inherited (extended) and used in other class
}
class MetaBottleMaker2 extends BottleMaker3 {
public material: string = "metal";
constructor() {
super(); // Initialize the parent class properties
}
accessName() {
console.log(this.name + ": ", this.material);
}
changeName() {
this.name = "Cello";
}
}
let b3 = new MetaBottleMaker2();
b3.accessName(); // This should now print "Milton: metal"
b3.changeName();
b3.accessName(); // This should print "Cello: metal"
//@Optional Class and Object Properties
class UserDets {
constructor(public readonly userName: string) {}
changeName() {
this.userName = "hellyow";
//readonly gives error when you try to change the variable's value
//Cannot assign to 'userName' because it is a read-only property
}
}
let u1 = new UserDets("Nikhil");
u1.changeName();
//@Classes and Objects: Parameter Properties
class UserData {
/*Parameter Properties: By prefixing a constructor parameter with an access modifier ( public, private, protected ) or the readonly modifier, TypeScript automatically performs two actions:
- Declares a class property: with the same name and type as the constructor parameter.
- Initializes that class property: with the value passed to the corresponding constructor parameter.
*/
constructor(
public name: string,
public age: number,
public gender?: string //This becomes optional
) {}
}
let ud1 = new UserData("Nikhil", 20, "Male");
let ud2 = new UserData("Alex", 18);
//@Getters and Setters in TypeScript
class People {
constructor(public _name: string, public age: number) {}
get name() {
return this._name;
}
set name(value: string) {
this._name = value;
}
}
let p1 = new People("Nikhil", 20);
console.log(p1._name);
p1.name = "Dhanashree";
//@Classes and Objects: Static Members
class Shery {
//static keywords makes variables or properties accessible without making a class instance of the class
//Means no use of new keyword to make an object, directly you can access it's variables and properties (methods)
static version: 2.1;
static getRandomNumber() {
return Math.random();
}
}
// let sh1 = new Shery(); --No use of this when static initialsed and if initialsed, it doesn't get added to Object
//@Classes and Objects: Abstract Classes
class Payments {
constructor(protected amount: number, protected account_no: number) {
this.amount = this.validateAmount(amount);
}
private validateAmount(amount: number): number {
if (amount > 0) {
return amount;
} else {
throw new Error("Amount must be greater than 0.");
}
}
}
//Abstract classes do not require instances to be created; they are used solely for inheritance and extending in other classes. They act as base classes, containing generic functionality. To make them more specific, they can be extended, and specific functionality can be added in the derived classes.
class Paytm extends Payments {}
//@Functions
function func1(): void {}
function func2(): string {
return "hellyew";
}
//@Function Types
function funct(name: string, callback: (arg: string) => void) {
callback("Nikudie");
}
funct("Nikhil", (arg: string) => {
console.log(arg);
});
//@Optional & Default Parameters
function personalDets(
name: string,
age: number,
gender: string = "Prefer not to say"
) {
console.log(name, age, gender);
}
personalDets("Nikhil", 20, "Male");
personalDets("Dhanashree", 20);
//@Rest/Spread Parameters/Operators
// function restParams(a: number, b:number, c:number....){}
//Too much params? need to define that much args in function!
// No need, just store it in an array using rest/spread operator
//Instead of defining individual parameters for each possible argument, you can use
// the 'rest' syntax (...) to collect them into an array and handle them
// dynamically. This approach is particularly useful when the number of
// arguments is not fixed or when dealing with a large number of parameters.
function restParams(...arr: number[]) {
console.log(arr);
}
restParams(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 74, 41, 741, 115);
//@Function Overloading
//TypeScript Function Signature
function funcOverload(a: string): void;
function funcOverload(a: string, b: number): number;
function funcOverload(a: any, b?: any) {
if (typeof a === "string" && b === undefined) {
console.log("Hey");
}
if (typeof a === "string" && typeof b === "number") {
return 123;
} else throw new Error("Something is wrong");
}
funcOverload("Hey");
funcOverload("Hey", 12);
//@Generics
//Generic functions
function genericFncs<T>(variable: T) {
console.log(variable);
}
genericFncs<string>("This is a string, no error");
genericFncs<number>(200); //200 means success, means no error because generics
genericFncs<boolean>(true);
genericFncs(
"Here, even if we don't mention type, TypeScript automatically inferences its type"
);
//#####################################
function log<T>(val: T) {
console.log(val);
}
log<string>("We replaced console.log to log<type>");
//Generic interfaces
interface GenericInterface<T> {
name: string;
age: number;
key: T;
}
function genericInterfaceFunc(obj: GenericInterface<string>) {}
genericInterfaceFunc({
name: "It'll take string",
age: 12,
key: "This is a generic interface",
});
//Generic classes
class GenericClass<T> {
constructor(public key: T) {}
}
let gc1 = new GenericClass<string>("Four Two One Two Two");
let gc2 = new GenericClass<number>(42122);
console.log(gc1, gc2);
//@Modules
import { addPayment, getDetails } from "./payment";
addPayment(741);
getDetails();
//@Type Assertion
let aVar: any = 12;
(aVar as string).charCodeAt;
(<number>aVar).toString;
//@Type Guards
function typeGuards(arg: string | number) {
// arg. (Here, the intellisense will suggest methods which are common to both string and number)
//Type Narrowing
if (typeof arg === "string") return "It's a string";
if (typeof arg === "number") return "It's a number";
else throw new Error("Only string and number is accepted in this function");
}
//Type Guard - instanceof
class TVRemote {
switchTvOff() {
console.log("TV Switched Off");
}
}
class CarRemote {
switchCarOff() {
console.log("Car Switched Off");
}
}
const tv = new TVRemote();
const car = new CarRemote();
function swithOffDevice(device: TVRemote | CarRemote) {
if (device instanceof TVRemote) device.switchTvOff();
else if (device instanceof CarRemote) device.switchCarOff();
}