How type comes into play with a class's constructor

The instantiation of a class calls the constructor of the class. If this one is not defined, nothing is called. When no constructor is defined, the parentheses do not have any argument. The constructor's goal is to provide initialization of data to the class:

const d = new Variables();

In the case where the parameters are defined, the initialization must provide all the non-optional parameters. In the following code, the instantiation calls the constructor that has two parameters:

class MyClass {
constructor(param1: number, param2: string) {
}
}
const myClassInstance = new MyClass(1, "Must be present");

A constructor is similar to a function but cannot have an override. There is only a single constructor that can be defined. By default, it is public if no visibility is provided:

class MyClass {
private m1: number;
private m2: string;
private m3: number;
constructor(param1: number, param2: string) {
this.m1 = param1;
this.m2 = param2;
this.m3 = 123;
}
}

However, a constructor can be overloaded by many signatures. Similar to a function, the use of many definitions is possible with the use of a semicolon. In the following example, you can see that it is possible to instantiate the class with a single number or with a number and a string:


class ClassWithConstructorOverloaded {
private p1: number;
private p2: string;

constructor(p1: number);
constructor(p1: number, p2?: string) {
this.p1 = p1;
if (p2 === undefined) {
p2 = "default";
}
this.p2 = p2;
}
}

If a class extends another class, it must call super with the parameter of the right type to the base class. The class that inherits the second class does not need to have the same number of constructor parameters, nor the same type. What is important is the call to super to respect the type of the extended class. In the following example, MyClass has a constructor that takes a number and a string. The class that extends MyClass, MyClass2, must call super with a number and a string. The example illustrates that the value can come from the constructor of the class or can be computed directly:

class MyClass2 extends MyClass {
constructor(p1: number) {
super(p1, "Here");
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.49.108