What is Constructor Typescript ?
In TypeScript, a constructor is a special method inside a class that is called automatically when you create a new instance of the class using the new keyword. Its primary purpose is to initialize the object's properties and perform any necessary setup during object creation.
Key characteristics of constructors:
Name: Must match the class name.
No return type: Constructors do not explicitly return a value, but they can implicitly return void.
Parameters: Can accept arguments to provide initial values for object properties.
Access modifiers: Can be public (accessible from anywhere), private (accessible only within the class), or protected (accessible within the class and subclasses).
Example:
TypeScript
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}!`);
}
}
const alice = new Person("Alice");
alice.greet(); // Output: "Hello, my name is Alice!"
Constructor Overloading:
TypeScript allows multiple constructors with different parameter lists for a single class, providing flexibility in object creation.
TypeScript
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
constructor(x: number) {
this.x = x;
this.y = 0;
}
}
const point1 = new Point(3, 4);
const point2 = new Point(5);
Advanced uses:
Optional parameters: Make some constructor parameters optional using the ? suffix.
Default parameter values: Provide default values for optional parameters.
Constructor chaining: Call another constructor from within a constructor using super().
Remember:
You can only have one public constructor, but multiple private or protected constructors are allowed.
Constructors are essential for initializing object state and ensuring proper object creation.
By understanding constructors and their capabilities, you can write well-structured and maintainable classes in your TypeScript projects.
Sources
1. https://github.com/Messiahhh/blog
No comments:
Post a Comment
Note: only a member of this blog may post a comment.