Constructors in TypeScript
A constructor is a special method within a class that is automatically invoked when we create an instance of that class. Its primary purpose is to initialize the properties of the current instance. In TypeScript, constructors allow us to set up the initial state of an object.
Example:
class Person {
constructor(public name: string, public age: number) {
// Initialize properties
}
}
const john = new Person('Uday', 20);
console.log(`Name: ${john.name}, Age: ${john.age}`);
Output:
[LOG]: "Name: Uday, Age: 20"
Explanation:
- We define a
Person
class with two properties:name
andage
. - The constructor takes two parameters (
name
andage
) and assigns their values to the corresponding properties.
// converted javascript code
var Student = /** @class */ (function () {
function Student(code, name) {
this.studName = name;
this.studCode = code;
}
Student.prototype.getGrade = function () {
return "A+";
};
return Student;
}());
TypeScript class
TypeScript classes play a crucial role in creating robust and maintainable code. In this article, we’ll learn TypeScript classes, explore their features, and learn how to optimize them for better search engine ranking. Typescript is an open-source programming language built over Javascript, also known as the Superset of Javascript. Typescript has more features when compared to Javascript. It supports Object-oriented programming features like classes, Interfaces, Polymorphism, etc.
Syntax to declare a class:
class class_name{
field;
method;
}