Friday, November 9, 2018

TypeScript - Classes - Introduction

To create a class, we need to use the class keyword. Consider the below example:

class City {
public cityName:string;
private type: string;
protected elevation: number;

constructor(name:string) {
this.cityName = name;
this.type = "city";
this.elevation = 505;
}

}

const currCity = new City("Hyderabad");
console.log(currCity);

Class helps us to create a blueprint for objects. This is a ES6 feature.

The public keyword makes the property available from outside the class. Here cityName is a public property.
The private keyword indicates private properties. That means, these properties are accessible from within the class.
We can create protected properties. Apart from being private, protected properties are also accessible from other classes which inherit from this class. That means, a child class has access to the parent properties. Basically, protected properties behave like private properties.

Note that we have setup these properties directly in the class body and not inside the constructor.

We can also provide a constructor function. We can also pass some arguments to it. In our example we have created a constructor function with a argument name.  It is assigned to the cityName private variable of the class City. To access the private variable inside the constructor, we use the keyword this. The this keyword is especially useful to resolve conflicts in names - especially when the name of the constructor argument and the name of the private property is the same.

To instantiate the class we use the new keyword. In our example currCity is the instance of the class City.



Reference:
https://www.typescriptlang.org/docs/handbook/classes.html

No comments:

Post a Comment