-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvanced.ts
More file actions
43 lines (33 loc) · 1.03 KB
/
advanced.ts
File metadata and controls
43 lines (33 loc) · 1.03 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
// Function Overloads
type Combinable = string | number;
type Numeric = number | boolean;
type Universal = Combinable & Numeric;
// These are overloads a description of how the function is used.
function add(a: string, b: string): string;
function add(a: number, b: number): number;
function add(a: Combinable, b: Combinable) {
if (typeof a === 'string' || typeof b === 'string') {
return `${a}${b}`;
}
return a + b;
}
// Without overloads this type is `string | number`.
const result = add('Gary', ' Coleman');
result.split(' ');
// Optional Chaining
const fetchedUser = {
id: '',
firstName: 'Gary',
// job: {
// title: 'actor',
// description: 'A crazy guy in movies.'
// },
};
// If fetched user exists then check job
console.log(fetchedUser?.job?.title);
// Nullish Coalescing
const userInput = null;
// If user input is falsy then it will switch to default.
const storedData1 = userInput || 'default';
// If user input is null or undefined then switch to default.
const storedData2 = userInput ?? 'default';