Get started with object oriented programming in Typescript.
Typescript behaves like a language with built-in support for OOP concepts, and does not carry the quirks of Javascript in that respect.
Classes and Objects
Define classes and objects like how you define in any of the popular OOP languages.
|
|
We have defined a simple class ‘Fruit’ and provided it with -
- a public variable of type string -
name
- a private variable of type array of strings -
grownIn
- constructor to set variable values from initialization
- method to get value of
getGrownIn
We define appleFruit
as an object of the class Fruit
and initialize it with values for both name
and grownIn
.
Straight off the bat we see the feature of private variables, which are a thing only in the most recent Javascript standard.
|
|
We also see how auto-complete works beautifully while typing in all this code.
Use interfaces
We can level-up the above code by using interfaces for additional abstraction.
|
|
We have specified two variables and both are optional.
Change the class to implement this interface.
|
|
Similar to other languages you can extend a parent class in the interface.
|
|