-
Notifications
You must be signed in to change notification settings - Fork 720
/
Copy path4-class-basics.ts
80 lines (68 loc) · 2.13 KB
/
4-class-basics.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
import { HasPhoneNumber, HasEmail } from "./1-basics";
// == CLASSES == //
/**
* (1) Classes work similarly to what you're used to seeing in JS
* - They can "implement" interfaces
*/
// export class Contact implements HasEmail {
// email: string;
// name: string;
// constructor(name: string, email: string) {
// this.email = email;
// this.name = name;
// }
// }
/**
* (2) This looks a little verbose -- we have to specify the words "name" and "email" 3x.
* - Typescript has a shortcut: PARAMETER PROPERTIES
*/
/**
* (3) Access modifier keywords - "who can access this thing"
*
* - public - everyone
* - protected - me and subclasses
* - private - only me
*/
// class ParamPropContact implements HasEmail {
// constructor(public name: string, public email: string = "no email") {
// // nothing needed
// }
// }
/**
* (4) Class fields can have initializers (defaults)
*/
// class OtherContact implements HasEmail, HasPhoneNumber {
// protected age: number = 0;
// // private password: string;
// constructor(public name: string, public email: string, public phone: number) {
// // () password must either be initialized like this, or have a default value
// // this.password = Math.round(Math.random() * 1e14).toString(32);
// }
// }
/**
* (5) TypeScript even allows for abstract classes, which have a partial implementation
*/
// abstract class AbstractContact implements HasEmail, HasPhoneNumber {
// public abstract phone: number; // must be implemented by non-abstract subclasses
// constructor(
// public name: string,
// public email: string // must be public to satisfy HasEmail
// ) {}
// abstract sendEmail(): void; // must be implemented by non-abstract subclasses
// }
/**
* (6) implementors must "fill in" any abstract methods or properties
*/
// class ConcreteContact extends AbstractContact {
// constructor(
// public phone: number, // must happen before non property-parameter arguments
// name: string,
// email: string
// ) {
// super(name, email);
// }
// sendEmail() {
// // mandatory!
// console.log("sending an email");
// }
// }