I replicated Object-Oriented Programming in Go to TypeScript. You can read the explanation or theory of OOP in that article. I'm here to show you how I technically replicated the code.
Abstraction
We created a class as a template to define an object. Of course, a class or object has properties and methods.
print() {console.log(this.name,'is a monster!!!')console.log(this.name,'has:')for(letabilityofthis.abilities){console.log('-',ability)}}
Let's create another form of the print method for the Monster class that prints abilities. Put the print method to the Monster class and execute the index.ts. We will see a different result.
Encapsulation
Encapsulation is about Access Modifiers. Let me explain about Interface and Constructor first.
The interface allows us to define a must-defined method for classes that implements it. Here, we created getters and setters for name, feet, and hasPaws.
No need to define properties anymore. We can create a monster in a single line.
Access Modifiers
There are three access modifiers in TypeScript; private, protected, and default (public). The private only allows to its class. The protected allows its sub-classes.
importAnimalfrom'./Animal'exportdefaultclassMonsterextendsAnimal{private_abilities: string[]=[];constructor(name: string,feet: number,hasPaws: boolean,abilities: string[]){super(name,feet,hasPaws);this.abilities=abilities;}protectedsetabilities(abilities: string[]){this._abilities=abilities;}protectedgetabilities():string[]{returnthis._abilities;}print() {console.log(this.name,'is a monster!!!')console.log(this.name,'has:')for(letabilityofthis.abilities){console.log('-',ability)}}}
Same thing for the Monster.
Closing
You can get the source code at https://github.com/aristorinjuang/ts-oop. Try to check out my references. They are good resources from official TypeScript. I didn't try static property or method, abstract class, decorator, overloads, or more. But I hope this article can give you a basic understanding of OOP in TypeScript.