1

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?

2
  • 1
    Declare those properties? e.g.: private message : string Commented Jul 28, 2016 at 10:11
  • I'll suggest you to read about classes in Typescript. It'll make your concept more clearer. typescriptlang.org/docs/handbook/classes.html Commented Jul 28, 2016 at 11:49

1 Answer 1

7

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) {}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Sure, thanks. This works. Coming from ES5, so my knowledge is pretty much nil, so I was wondering if this is the way forward with having the constructor like we have in C#. What would I lose if I omit the constructor and just have class level variables?
See my revised answer

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.