rds80
rds80

Reputation: 629

creating properties in constructor

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>

}

Upvotes: 0

Views: 984

Answers (2)

Andr&#233; Pacheco
Andr&#233; Pacheco

Reputation: 1885

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.

Upvotes: 1

Mateusz Kocz
Mateusz Kocz

Reputation: 4602

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.

Upvotes: 1

Related Questions