36

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?

3 Answers 3

49

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

Sign up to request clarification or add additional context in comments.

1 Comment

Some of these links are dead now. Current official docs about constructors: typescriptlang.org/docs/handbook/2/classes.html#constructors
17

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.

2 Comments

Just been caught by this one, with there was more explcit information on this somewhere.
Regarding the derived classes, here is from the TypeScript spec, 8.3.3 Automatic constructors: "In a derived class, the automatic constructor has the same parameter list (and possibly overloads) as the base class constructor. The automatically provided constructor first forwards the call to the base class constructor using a call equivalent to BaseClass.apply(this, arguments); and then executes the instance member variable initializers, if any".
12

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.