Issue
here are the basic class Person and subclass Student
class Person {
constructor(private name:string){}
}
class Student extends Person {
greet(){
console.log('Hi, I'm ' + this.name)
}
}
and I got the error:
Property 'name' is private and only accessible within class 'Person'.
according to the docs about Automatic Constructors
In a derived class, the automatic constructor has the same parameter list (and possibly overloads) as the base class constructor.
so I thought the constructor of class Student would invoke the constructor of Person. I mean it is just reference call. so I thought the class Student should have its own property name
and what should I do to make sure that the class Student has its own property name?
Solution
You need to change private to protected. from typescriptlang.org:
TypeScript’s private # TypeScript also has it’s own way to declare a member as being marked private, it cannot be accessed from outside of its containing class.
-- means private fields are going to be in all subclasses but you won't be able to access it.
Understanding protected # The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed within deriving classes.
-- it's what you need, the fields which can't be access from outside but available in all subclasses.
Answered By - lebed2045
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.