object oriented programming typescript

Solutions on MaxInterview for object oriented programming typescript by the best coders in the world

showing results for - "object oriented programming typescript"
Martín
01 Apr 2019
1// Example using an Animal
2class Animal {
3    // We have access modifiers (public, private, protected)
4    // Each member is public by default
5    // Below line is equivalent to 'public name: string'
6    name: string;
7
8    // Constructor
9    constructor(name: string) {
10        this.name = name;
11    }
12
13    // Function / Method
14    move(distanceInMeters = 0) {
15        console.log(`${this.name} moved ${distanceInMeters}m.`);
16    }
17}
18
19class Leg {
20    // private access modifier
21    private length: number;
22
23    constructor(length: number) {
24        this.length = length;
25    }
26
27    // Getters
28    getLength() {
29        return this.length;
30    }
31
32    // Setters
33    setLength(newLength: number) {
34        this.length = newLength;
35    }
36}
37
38// Inheritance - A dog IS AN Animal
39class Dog extends Animal {
40    // Composition - A dog HAS A Leg (really 4, but this will do for explanation purposes :D)
41    leg: Leg;
42
43    constructor(name: string, legLength: number) {
44        super(name);
45        this.leg = new Leg(legLength);
46    }
47
48    bark() {
49        console.log("Woof! Woof!");
50    }
51}
52
53// See it in action!
54const dog = new Dog("Buddy", 10);
55dog.move(10); // Output - Buddy moved 10m.
56dog.bark(); // Output - Woof! woof!
57dog.leg.getLength(); // Returns - 10
58dog.leg.setLength(15); // Sets leg length to 15
59dog.leg.getLength(); // Returns - 15
60
61// Example of inheritance and overriding parent class function/method
62class Snake extends Animal {
63    constructor(name: string) {
64        super(name);
65    }
66
67    // overrides move function/method in parent Animal class
68    move(distanceInMeters = 5) {
69        console.log(`${this.name} slithered ${distanceInMeters}m.`);
70    }
71}
72
73// See it in action!
74const snake = new Snake("Slippy");
75snake.move(); // Output - Slippy slithered 5m.
76snake.move(20); // Output -  Slippy slithered 20m.