-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplayground.ts
475 lines (377 loc) · 9.44 KB
/
playground.ts
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/* eslint-disable */
// !---------------
// ! Type Coercion in TypeScript
// !---------------
const one = true + false;
const two = 1 + "hello world" + 4;
const three = 1 + true;
const four = "hello" + true;
// !---------------
// ! Type Inference
// !---------------
// type inferred
let myName = "John";
myName = 8; // type error!
// ! Function types
// infers '5 | undefined' return type
const myFct2 = () => (Math.random() > 0.5 ? 5 : undefined);
// infers 'void' return type
const myFct3 = () => {
console.log("Hello, world!");
};
// inferred return type
const myFct4 = (name: string, surname?: string) => {
return name + surname;
};
const resultOfMyFct2 = myFct2();
// !-----------------
// ! Types vs. Values
// !-----------------
// ! type 'undefined' vs. value 'undefined'
let age2: number | undefined | null = 4;
age2 = undefined;
// !------------------
// ! Interface merging
// !------------------
interface MyBookT {
title: string;
isbn: string;
}
interface MyBookT {
price: number;
}
// !------------------
// ! Excess properties
// !------------------
type MyMagazineT = { title: string; issn: string };
type ReadingMaterialT = MyBookT | MyMagazineT;
const readingMaterial: ReadingMaterialT[] = [
{
title: "New Covid-19 vaccine",
isbn: "978-3401002569",
price: 9,
},
{
title: "Robinson Crusoe",
issn: "21212-212",
},
];
// ! Attention: No excess property check if MyMagazinT only contains `title` (no `issn`)!
// See https://stackoverflow.com/questions/70253737/union-of-two-objects-where-one-is-the-subtype-of-the-other-is-not-type-safe
// ! Typescript is not a sound type system
// !--------------------------------------
type Books = Array<{ isbn: string; title: string }>;
let books: Books = [
{
isbn: "sadasfd",
title: "ein buch",
},
{
isbn: "sadasfd",
title: "ein zweites buch",
},
];
const books2 = [
{
isbn: "sadasfd",
title: "ein buch",
nochwas: "ein buch",
},
{
isbn: "sadasfd",
title: "ein zweites buch",
nochwas: "ein zweites buch",
},
];
books = books2;
// ! Allow excess properties
// ! -----------------------
type Car = {
wheels: number;
engine: string;
// Allow excess properties
[key: string]: unknown;
};
const MyTesla: Car = {
wheels: 4,
engine: "electric",
cameras: 20,
};
// Alternative: Intersection with Record.
// !----------------------------
// ! Function (parameter values)
// !----------------------------
const myFunction4 = (a: number, b: number) => a + b;
function buildName(firstName: string, lastName?: string) {
if (lastName !== undefined) {
return firstName + " " + lastName;
} else {
return firstName;
}
}
function buildName2(firstName: string, lastName?: string) {
// TS does not complain. Returns undefined.
return lastName;
}
console.log(buildName2("Andre"));
// !-------------------
// ! Strict null checks
// !-------------------
let firstName: string[] | null = undefined; // not possible in strict mode
function myFunction3(hello?: string): string {
if (hello) {
return hello;
}
return "";
}
// let firstName: string | undefined | null = null;
let age: number | undefined = undefined;
let isEmployed: boolean; // undefined
// Array of strings
const list: Array<string> = ["foo", "bar"];
// ReadonlyArray of numbers
const secondList: ReadonlyArray<number>;
list[0] = 5; // Error
// !--------------------------------
// ! Functions - Optional parameters
// !--------------------------------
const myFunction = (input: string): number => 4;
function myFunction2(hello?: string) {
return hello;
}
const myFunction2 = (arg?: number) => 4;
myFunction2(null);
const myArray2: unknown[] = [1.2, 222.1, 3444];
// !--------------------------------
// ! Interface vs. type alias
// !--------------------------------
interface Address {
street: string;
zipCode: string;
city: string;
}
type AddressT = {
street: string;
zipCode: string;
city: string;
};
// !---------------
// ! Intersection
// !---------------
type Book = {
id: string;
isbn: string;
title: string;
pages?: number;
};
type Magazine = Book & {
coverUrl: string;
// duplicate isbn
isbn: number;
};
const magazin: Magazine = {
id: "1",
title: "Eloquent JavaScript",
isbn: 9781593272821, // Error: Type 'string' is not assignable to type 'never'
coverUrl: "https://www.foo.bar",
};
type MagazinWithNewIsbn = Omit<Magazine, "isbn"> & { isbn: number };
const magazine2: MagazinWithNewIsbn = {
id: "1",
isbn: 123,
title: "Vogue",
};
// !---------------
// ! Intersection: Use case example
// !---------------
type BookGeneral = {
// id is of type `number` when synced with DB and of type `string` in offline mode.
id: number | string;
isbn: string;
title: string;
pages?: number;
};
type BookSynced = Omit<BookGeneral, "id"> & { id: number };
//! Impossible type -> never type
type IsbnIntersection = string & number;
// const myString: never = 'string';
const ghost: never;
const myNothing: string = ghost;
// !--------------------
// ! Interface extension
// !--------------------
interface BookI {
id: string;
isbn: string;
}
// Error: Type 'number' is not assignable to type 'string'
// ! Each field in the child has to be a subtype of its corresponding field
// ! in the parent (covariance on members).
interface MagazineI extends BookI {
isbn: number;
}
// !---------------
// ! Generics
// !---------------
// ! Generic function
const loggingIdentity = <T>(arg: T): T => {
console.log(arg);
return arg;
};
// ! Generic object
type ResponseT<T> = {
id: number;
data: T[];
createdAt: number;
modifiedAt: number;
};
const response: ResponseT<Book> = {
id: 1,
data: [{ isbn: "abc", title: "Faust" }],
createdAt: 12345678,
modifiedAt: 12345678,
};
// ! Generic array
const myArray: Array<AddressT> = [
{
street: "Alexanderplatz",
zipCode: "USA2134",
city: "asdf",
},
];
interface Profile {
id: number;
gender: string;
name: string;
pictureUrl?: string;
address: Address;
}
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "Michael",
age: 65,
};
let book: { isbn: string; title: string };
// let person: { name: string, age: number };
// person = {
// name: 'Michael',
// age: 65,
// }
// !---------------
// ! Type guards
// !---------------
// ! `in` operator for custom type guards
type Fish = { swim: () => void };
type Bird = { fly: () => void };
type Human = { swim?: () => void; fly?: () => void };
function move(animal: Fish | Bird | Human) {
if ("swim" in animal) {
animal.swim;
// animal.swim();
} else {
animal.fly;
// animal.fly();
}
}
move({});
// ! `type predicates` aka user-defined type guards
function isFish(animal: Fish | Bird): animal is Fish {
return (animal as Fish).swim !== undefined;
}
// Both calls to 'swim' and 'fly' are now okay.
function move2(animal: Fish | Bird) {
if (isFish(animal)) {
animal.swim();
} else {
animal.fly();
}
}
move2({ swim: () => {} });
// !--------------------------------------------
// ! `void` and `never` as function return types
// !--------------------------------------------
// ! void
// ! -------------------
// NOTE: Contextual typing with a return type of `void` does not force functions to not return something.
// (see https://www.typescriptlang.org/docs/handbook/2/functions.html#return-type-void)
// Expected: void does NOT allow return value
const noop2 = (): void => {
return true;
};
// What??? 🤯: void allows return value
const noop1: () => void = () => {
return true;
};
const thisIsVoid = noop1();
// Explanation
const src = [1, 2, 3];
const dst = [0];
// TS decided to introduce this weird definition of void so that the following is allowed:
src.forEach((el) => dst.push(el));
// Although technically speacking it should be written as:
src.forEach((el) => {
dst.push(el);
});
// ! never
// ! -------------------
type NotPossible = boolean & never;
type WillBeBoolean = boolean | never;
// ! `never` NOT possible here as type (function does implicitly return at some point)
const boolOrThrow = (): void => {
if (Math.random() > 0.5) {
throw new Error("hello");
}
// ! implicitly:
// return undefined
};
// ! `void` also possible here as type
const alwaysThrow = (): never => {
if (Math.random() > 0.5) {
throw new Error("hello");
}
throw new Error("goodbye");
};
// returns `number` (even though it throws) (`number` is same as `number | never`)
const numberFunction = (): number | never => {
if (Math.random() > 0.5) {
throw new Error("hello");
} else {
return 1;
}
};
export {};
// !-------------------------------------------------
// ! Type of normalize function from playground_02.js
// !-------------------------------------------------
/**
* Function to transform an array into an object.
* This decreases access to array elements by id from O(n) to O(1).
* O(1) is equivalent to a direct access in only one calculation step.
*
* Example: This array
*
* [
* { id: 1, name: "foo" },
* { id: 2, name: "bar" },
* { id: 3, name: "baz" },
* ];
*
* gets transformed into this object:
*
* {
* 1: { id: 1, name: 'foo' },
* 2: { id: 2, name: 'bar' },
* 3: { id: 3, name: 'baz' },
* };
*
* @param data Array of data to be normalized
* @returns object structure of the data array
*/
const normalize = <T extends { id: string }>(data: T[]): Record<string, T> =>
data.reduce((accumulator, currentValue) => {
accumulator[currentValue.id] = currentValue;
return accumulator;
}, {});