Animesh D
Animesh D

Reputation: 5002

Is having constructor necessary in Typescript code?

I generated a new Aurelia project using aurelia-cli with the au new command.

This is the app.ts given to me:

export class App {
  message = 'Hello World!';
}

I updated my app.ts with the app.ts from this tutorial like this:

export class App {
  constructor() {
    this.message = 'Hello World!';
    this.firstName = "Animesh";
    this.lastName = "Bulusu";
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

I can see the expected output when I refresh the page, but I get these errors in the Errors console.

Property 'message' does not exist on type 'App'.
Property 'lastName' does not exist on type 'App'.
Property 'lastName' does not exist on type 'App'.

If I remove the constructor and place the variables directly inside the class, these errors go away. Why is that and how do I get rid of these errors?

Upvotes: 1

Views: 112

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164307

You need to declare the members:

class App {
    private message: string;
    private firstName: string;
    private lastName: string;

    constructor() {
        this.message = 'Hello World!';
        this.firstName = "Animesh";
        this.lastName = "Bulusu";
    }
 }

And then the errors will go away.


Edit

If your initial member values are constants, and you don't need to initialize anything when creating a new instance then there's no need for a constructor:

class App {
    private message = 'Hello World!';
    private firstName = "Animesh";
    private lastName = "Bulusu";
}

(notice that there's also no need here to specify the type of the members as the compiler can infer that they are strings)

Also, if you want the members to be assigned with values passed to the constructor then you can also use the shortcut (which I'm pretty sure comes from C#):

class App {
    constructor(private message: string, public name: string) {}
}

Upvotes: 7

Related Questions