forked from mike-works/typescript-fundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
8-declaration-merging.ts
97 lines (74 loc) · 2.14 KB
/
8-declaration-merging.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
/**
* (1) "identifiers" (i.e., a variable, class, function, interface)
* - can be associated with three things: value, type and namespace
*/
// function foo() {}
// interface bar {}
// namespace baz {
// export const biz = "hello";
// }
// // how to test for a value
// const x = foo; // foo is in the value position (RHS).
// // how to test for a type
// const y: bar = {}; // bar is in the type position (LHS).
// // how to test for a namespace (hover over baz symbol)
// baz;
// export { foo, bar, baz }; // all are importable/exportable
/**
* (2) Functions and variables are purely values.
* - Their types may only be extracted using type queries
*/
// const xx = 4;
// const yy: typeof xx = 4;
/**
* (3) Interfaces are purely types
*/
// interface Address {
// street: string;
// }
// const z = Address; // 🚨 ERROR (fails value test)
/**
* (4) Classes are both types _and_ values
*/
// class Contact {
// name: string;
// }
// // passes both the value and type tests
// const contactClass = Contact; // value relates to the factory for creating instances
// const contactInstance: Contact = new Contact(); // interface relates to instances
/**
* (5) declarations with the same name can be merged, to occupy the same identifier
*/
// class Album {
// label: Album.AlbumLabel = new Album.AlbumLabel();
// }
// namespace Album {
// export class AlbumLabel {}
// }
// interface Album {
// artist: string;
// }
// let al: Album; // type test
// let alValue = Album; // value test
// export { Album }; // 👈 hover over the "Album" -- all three slots filled
/**
* (6) Namespaces have their own slot, and are also values
*/
// // 💡 they can be merged with classes
// class AddressBook {
// contacts!: Contact[];
// }
// namespace AddressBook {
// export class ABContact extends Contact {} // inner class
// }
// const ab = new AddressBook();
// ab.contacts.push(new AddressBook.ABContact());
// // 💡 or functions
// function format(amt: number) {
// return `${format.currency}${amt.toFixed(2)}`;
// }
// namespace format {
// export const currency: string = "$ ";
// }
// format(2.314); // $ 2.31
// format.currency; // $