All the examples I see show a class with a constructor. Is it ok to not put a constructor in? a lot like how C# automatically makes you a default empty constructor?
A constructor is a special function of the class that is responsible for initializing the variables of the class. TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class.
Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.
The TypeScript docs have a great example of constructor usage: class Greeter { greeting: string; constructor(message: string) { this. greeting = message; } greet() { return "Hello, " + this. greeting; } } let greeter = new Greeter("world");
You can do this by using the new keyword, followed by a syntax similar to that of an arrow function, where the parameter list contains the parameters expected by the constructor and the return type is the class instance this constructor returns. The TypeScript compiler now will correctly compile your code.
From the spec, section 8.3 (8.3):
A class may contain at most one constructor declaration. If a class contains no constructor declaration, an automatic constructor is provided, as described in section 8.3.3. (8.3.3.)
Correct. Classes in TypeScript do not require you to explicitly write a constructor. However if you are extending a base class you will need to create a constructor to call super() at a minimum.
Just to extend the accepted answer and correct an answer by Jon Gear (TS might have changed in the meantime):
Derived class does not need to create a constructor with the sole purpose to call super()
.
https://stackblitz.com/edit/no-need-for-derived-constructor?file=index.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With