Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a class NEED a constructor in Typescript?

Tags:

typescript

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?

like image 270
Grofit Avatar asked Mar 25 '13 17:03

Grofit


People also ask

Why do we use constructor in TypeScript?

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.

Does a class require a constructor?

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.

How do I create a constructor for a class in TypeScript?

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");

How do you use a class in TypeScript?

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.


3 Answers

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.)

like image 167
Ryan Cavanaugh Avatar answered Sep 18 '22 22:09

Ryan Cavanaugh


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.

like image 34
Jon Gear Avatar answered Sep 20 '22 22:09

Jon Gear


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

like image 27
Juraj Plavcan Avatar answered Sep 17 '22 22:09

Juraj Plavcan