Reputation: 30208
I am just learning TypeScript
so this is a newb question, but Google and even SO failed to help.
Given this code:
class Student implements IPerson {
public fullname: string = firstname + " " + middleinitial + " " + lastname;
constructor(public firstname, public middleinitial, public lastname) {
// this.fullname = firstname + " " + middleinitial + " " + lastname;
}
}
function greeter(person: IPerson) {
return "Hello, " + person.fullname;
}
when I try to assign to fullname
in the initial declaration:
public fullname: string = firstname + " " + middleinitial + " " + lastname;
TypeScript
is saying that firstname
, middleinitial
and lastname
don't exist, yet somehow, the compiled code works as expected. What am I doing wrong here? I understand I can assign the auto gen props in the constructor
(as is shown in the comment) but that is not always what I need...
Upvotes: 0
Views: 44
Reputation: 4647
To access a property in the current class, you have to prefix it with this
.
public fullname: string = this.firstname + " " + this.middleinitial + " " + this.lastname;
It works without using this
inside the constructor because the parameters have those names.
Upvotes: 3