5

I am analyzing some TypeScript code and I came across this kind of declaration inside a class definition:

constructor(readonly constructorParam : Type) {
  // here we don't assign constructorParam to anything
}

But further, I see that constructorParam is used as normal.

Is it possible that it constructorParam property is "created and assigned be default"?

It also is wrapped in export abstract class ... extends ... implements ... (while extends and implement are understandable inheritance keywords, export is used for working with modules, but might be relevant to discussion).

UPDATE

According to this post, it really seems to work like that - creating property and assigning value by default for constructor parameters marked as readonly.

5
  • 1
    Yes that totally works and isn't only limited to readonly. It saves time assigning each parameter in the constructor. E.g. the following is also possible: constructor(public randomVal: number) {} Commented Dec 9, 2019 at 8:32
  • 2
    @r3dst0rm And it would create and assign property randomVal ? Commented Dec 9, 2019 at 8:33
  • 1
    Indeed. Assuming it were the constructor of RandomClass, using it like: new RandomClass(5).randomVal would return passed in number 5. Commented Dec 9, 2019 at 8:35
  • You can read about it here: typescriptlang.org/docs/handbook/… Commented Dec 9, 2019 at 8:37
  • Link to updated handbook: typescriptlang.org/docs/handbook/2/… Commented Aug 23, 2022 at 14:43

2 Answers 2

7

According to this article, there exists shorthand to declare all class properites as contructor parameters like:

constructor ( public someProp : number )

In this case someProp will be created. Obviously, this is fully qualified declaration, i.e. we have type declaration (number in this case) and access modifiers and more, so instead of public it could be, for example, private readonly.

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

Comments

0

You can do something like this:

constructor(readonly construcotrParam : Type = "Normal") {
  // here we don't assign construcotrParam to anything
}

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.