javascript - Is having constructor necessary in Typescript code? -
i generated new aurelia project using aurelia-cli
au new
command.
this app.ts
given me:
export class app { message = 'hello world!'; }
i updated app.ts
app.ts
tutorial this:
export class app { constructor() { this.message = 'hello world!'; this.firstname = "animesh"; this.lastname = "bulusu"; } fullname() { return `${this.firstname} ${this.lastname}`; } }
i can see expected output when refresh page, these errors in errors console.
property 'message' not exist on type 'app'.
property 'lastname' not exist on type 'app'.
property 'lastname' not exist on type 'app'.
if remove constructor , place variables directly inside class, these errors go away. why , how rid of these errors?
you need declare members:
class app { private message: string; private firstname: string; private lastname: string; constructor() { this.message = 'hello world!'; this.firstname = "animesh"; this.lastname = "bulusu"; } }
and errors go away.
edit
if initial member values constants, , don't need initialize when creating new instance there's no need constructor:
class app { private message = 'hello world!'; private firstname = "animesh"; private lastname = "bulusu"; }
(notice there's no need here specify type of members compiler can infer strings)
also, if want members assigned values passed constructor can use shortcut (which i'm pretty sure comes c#):
class app { constructor(private message: string, public name: string) {} }
Comments
Post a Comment