-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeywords.ts
More file actions
66 lines (48 loc) · 1.28 KB
/
keywords.ts
File metadata and controls
66 lines (48 loc) · 1.28 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
/***** operators / keywords *****/
// 'is' keyword, type predicates, type guards
type Hobbies = "fishing" | "hunting";
interface Hobby {
hobbies: Hobbies
}
class Fishing implements Hobby {
hobbies: Hobbies = "fishing";
castReel(): void {
console.log("This hobby requires a fishing rod/reel to cast!");
}
}
class Hunting implements Hobby {
hobbies: Hobbies = "hunting";
inDeerStand(): void {
console.log("Patiently waiting for a deer...");
}
}
// type predicate
// 'hobby is Fishing' is the type predicate
function isFishing(hobby: Hobby): hobby is Fishing {
return hobby.hobbies === 'fishing';
}
function isHunting(hobby: Hobby): hobby is Hunting {
return hobby.hobbies === 'hunting';
}
const h1: Hobby = new Fishing();
const h2: Hobby = new Hunting();
if (isFishing(h1)) {
h1.castReel();
}
if (isHunting(h2)) {
h2.inDeerStand();
}
console.log();
// type guard 'typeof'
function padLeft(padding: number | string, input: string) {
if (typeof padding === "number") {
return " ".repeat(padding) + input;
}
return padding + input;
}
let paddedString = padLeft(5, "pad this string.");
console.log(paddedString);
paddedString = padLeft("-----", "pad this string.");
console.log(paddedString);
console.log();
export { }