forked from sjimenez77/typescript-play
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclasses.ts
105 lines (85 loc) · 2.13 KB
/
classes.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
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return 'Hello, ' + this.greeting;
}
}
let greeter = new Greeter('world');
///////////////////////////////////////////////////////////////////////////
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) {
super(name);
}
move(distanceInMeters = 5) {
console.log('Slithering...');
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) {
super(name);
}
move(distanceInMeters = 45) {
console.log('Galloping...');
super.move(distanceInMeters);
}
}
let sam = new Snake('Sammy the Python');
let tom: Animal = new Horse('Tommy the Palomino');
sam.move();
tom.move(34);
///////////////////////////////////////////////////////////////////////////
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee('Howard', 'Sales');
console.log(howard.getElevatorPitch());
console.log(howard.name); // error
///////////////////////////////////////////////////////////////////////////
let passcode = 'secret passcode 2';
class Employee2 {
private _fullName: string;
constructor(_fullname: string) {
this._fullName = _fullname;
}
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == 'secret passcode') {
this._fullName = newName;
} else {
console.log('Error: Unauthorized update of employee!');
}
}
}
let employee = new Employee2('Bad Name');
employee.fullName = 'Bob Smith';
if (employee.fullName) {
console.log(employee.fullName);
}