0

I'm going thru a tutorial and the author creates the properties of a class in the constructor. Is there a reason to do it this way instead of creating the properties in the class itself?

My background is C# so the reason why I would pass a parameter in the constructor is to make sure that when the class is instantiated, the arguments in the constructor are passed.

Here is the code that the author wrote:

export class Exercise {
    constructor(
        public name: string,
        public title: string,
        public description: string,
        public image: string,
        public nameSound?: string,
        public procedure?: string,
        public videos?: Array<string>
    ) {

    }
}

This is the way that I create the class:

export class Exercise {

    public name: string,
    public title: string,
    public description: string,
    public image: string,
    public nameSound?: string,
    public procedure?: string,
    public videos?: Array<string>

}

2 Answers 2

1

Defining parameters in the constructor with the access modifier (public, private, protected) allows you to assign values during the class' instantiation.

class MyConvenientClass {
  constructor(public myProp: string) {}
}
const myInstance = new MyConvenientClass('someValue')

If you only declare those properties, you'll have to assign them later which is not that convenient.

class MyMundaneClass {
  public myProp: string
}
const myInstance = new MyMundaneClass()
myInstance.myProp = 'someValue'

There's also one more difference. If you set the strictPropertyInitialization flag in the TS config, then you'll have to change the myProp typing in the MyMundaneClass to string | undefined. This is because TS can't tell for sure the value will always be there and hence requires you to explicitly state this possibility.

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

Comments

1

When you create the attributes in the constructor, for example:

constructor (public x: string) {
}

It is the same thing of:

public x: string;
constructor (x: string) {
    this.x = x;
}

So, you just do the same thing, but writing a little bit less.

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.