-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypescript-tutorial.ts
More file actions
332 lines (244 loc) · 9.04 KB
/
typescript-tutorial.ts
File metadata and controls
332 lines (244 loc) · 9.04 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
// Function types
//--------------------------------------------
// function calculate(num1: number, num2: number) {
// return num1 + num2;
// }
// 1. Functional array (generic)
// function getTotal(numbers: Array<number>) {
// return numbers.reduce((acc, item) => {
// return acc + item;
// }, 0);
// }
// 2. Functional array
// function getTotal(numbers: number[]) {
// return numbers.reduce((acc, item) => {
// return acc + item;
// }, 0);
// }
// console.log(getTotal([3, 2, 1]));
// Optional types
//--------------------------------------------
// type User = {
// name: string;
// age: number;
// address?: string; // this is optional
// };
// Union types
//--------------------------------------------
// type ID = number | string;
// Custom types
//--------------------------------------------
// type ID = number;
// Functional retun types
//--------------------------------------------
// function login(userData: User): User {
// return userData;
// }
// Type alias
//--------------------------------------------
// Note : cannot create duplicate type
// Note: interface create duplicates
// Note: interface used for object
// type User = { // name should be start as capitalize
// name: string;
// age: number;
// address?: string;
// };
// 1. used Type alias
// const user: User = {
// name: 'hello',
// age: 30
// }
// 2. used in Function
// function login(userData: User) {
// return userData;
// }
// 2. used in Function return
// function login(userData: User): User {
// return userData;
// }
// Interfaces (same as type alias)
//--------------------------------------------
// Note : cannot create duplicate type
// Note: interface create duplicates
// Note: interface used for object
// interface Transaction { // name should be start as capitalize
// payerAccountNumber: number;
// payeeAccountNumber: number;
// }
// interface BankAccount {
// accountNumber: number;
// accountHolder: string;
// balance: number;
// isActive: boolean;
// transactions: Transaction[];
// }
// const transaction1: Transaction = {
// payerAccountNumber: 123,
// payeeAccountNumber: 455,
// };
// const transaction2: Transaction = {
// payerAccountNumber: 123,
// payeeAccountNumber: 456,
// };
// const bankAccount: BankAccount = {
// accountNumber: 123,
// accountHolder: 'John Doe',
// balance: 4000,
// isActive: true,
// transactions: [transaction1, transaction2],
// };
// Typescript Extends interfaces
//--------------------------------------------
// Note : extend an interface that allows you to copy the properties and methods of one interface to another.
// Note : We can extend the Interfaces in TypeScript to include other interfaces. This helps us to create a new interface consisting of definitions from the other interfaces. Extending interfaces gives us more flexibility in how we define our interfaces and reuse the existing interfaces.
// interface Book {
// name: string;
// price: number;
// }
// interface EBook extends Book { // here we can access Book types
// fileSize: number;
// format: string;
// }
// interface AudioBook extends EBook { // here we can access EBook types
// duration: number;
// }
// const book: AudioBook = {
// duration: 4,
// };
// Merge
//--------------------------------------------
// Note : Merge more than one interfaces
// interface Book {
// name: string;
// price: number;
// }
// interface Book {
// size: number;
// }
// const book: Book = {
// name: 'Atomic habits',
// price: 1200,
// size: 45,
// };
// Narrowing with unions
//--------------------------------------------
// 1. Example
// type ID = number | string;
// function printId(id: ID) {
// if (typeof id === 'string') {
// console.log(id.toUpperCase());
// } else {
// console.log(id);
// }
// }
// printId('1');
// 2. Example // this function is autometic decide what is return types
// function getFirstThree(x: string | number[]) {
// return x.slice(0, 3);
// }
// console.log(getFirstThree([1, 2, 3, 4, 5]));
// Generics
//--------------------------------------------
// Note : Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.
// 1. Example
// function logString(arg: string) {
// console.log(arg);
// return arg;
// }
// function logNumber(arg: number) {
// console.log(arg);
// return arg;
// }
// function logArray(arg: any[]) {
// console.log(arg);
// return arg;
// }
// function logAnything<T>(arg: T): T { // this is generics used, T as a placeholder
// console.log(arg);
// return arg;
// }
// logAnything(['hello']);
// 2. Example
// interface HasAge {
// age: number;
// }
// function getOldest<T extends HasAge>(people: T[]): T {
// return people.sort((a, b) => b.age - a.age)[0];
// }
// const people: HasAge[] = [{ age: 30 }, { age: 40 }, { age: 10 }];
// interface Player {
// name: string;
// age: number;
// }
// const players: Player[] = [
// { name: 'John', age: 30 },
// { name: 'Jane', age: 35 },
// { name: 'Joe', age: 16 },
// ];
// // Assertion
// // const person = getOldest(players) as Player;
// const person = getOldest(people);
// person.age;
// 3. Example
// interface IPost {
// title: string;
// id: number;
// description: string;
// }
// interface IUser {
// id: number;
// name: string;
// age: number;
// }
// const fetchPostData = async (path: string): Promise<IPost[]> => {
// const response = await fetch(`http://example.com${path}`);
// return response.json();
// };
// const fetchUsersData = async (path: string): Promise<IUser[]> => {
// const response = await fetch(`http://example.com${path}`);
// return response.json();
// };
// const fetchData = async <ResultType>(path: string): Promise<ResultType> => {
// const response = await fetch(`http://example.com${path}`);
// return response.json();
// }
// (async () => {
// // const posts = await fetchPostData('/posts');
// const posts = await fetchData<IPost[]>('/posts');
// posts[0].
// })();
// Structural typing or duck typing
//--------------------------------------------
// Note : 2 object ka shape same he to iska matble typscript ke hisab se vo ek same type ka object hota he
// Note : This example shows how we can have two different interfaces with no declared relations between them and a method to receive one of them. As we can see, there is no problem if we call the method “stringifyAge” passing a variable declared with another type (the “ICar” interface in this case).
// Note : The only thing that matters is that the received param has the required properties (“age:number”). In our example it could lead us to a failure, maybe the “age” in one is in years and the other one in months or the age of the model.
// interface ICreadential {
// username: string;
// password: string;
// isAdmin?: boolean;
// }
// function login(credentials: ICreadential): boolean {
// console.log(credentials);
// return true;
// }
// const user = {
// username: 'codersgyan',
// password: 'secret',
// isAdmin: true,
// };
// login(user);
// interface IAuth {
// username: string;
// password: string;
// login(username: string, password: string): boolean;
// }
// const auth: IAuth = {
// username: 'codersgyan',
// password: 'secret',
// login(username: string, password: string) {
// return true;
// }
// }
// inference
// let num = 'Coders';